我嘗試使用 .append() .insertAdjacentHTML() 和 .insertAfter() 將每個影像的 alt 文本移動到其兄弟元素,但它沒有按預期作業......
目標結果是:
Image 1
Caption 1
Image 2
Caption 2
var altText = $("img").attr("alt");
$("span#here").append(altText);
.wrap {
margin-bottom: 10px;
}
.demo-img {
width: 280px;
}
span#here {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrap">
<img src="https://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RE4Y5jq?ver=ac72&q=90&m=6&h=201&w=358&b=#FFFFFFFF&l=f&o=t&aim=true" alt="Example Image Caption 1" class="demo-img">
<span id="here"></span>
</div>
<div class="wrap">
<img src="https://cdn-dynmedia-1.microsoft.com/is/image/microsoftcorp/gldn-M365-CP-Microsoft365-Commercial?wid=380&hei=213&fit=crop" alt="Example Image Caption 2" class="demo-img">
<span id="here"></span>
</div>
如果有人能提供幫助,不勝感激,謝謝!
uj5u.com熱心網友回復:
沒有一個班輪可以做到這一點。您需要遍歷影像并在回圈中設定文本
$(".wrap img").each(function (_, img) {
const alt = img.alt;
$(img).next("span").text(alt);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrap">
<img src="https://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RE4Y5jq?ver=ac72&q=90&m=6&h=201&w=358&b=#FFFFFFFF&l=f&o=t&aim=true" alt="Example Image Caption 1" class="demo-img">
<span id="here"></span>
</div>
<div class="wrap">
<img src="https://cdn-dynmedia-1.microsoft.com/is/image/microsoftcorp/gldn-M365-CP-Microsoft365-Commercial?wid=380&hei=213&fit=crop" alt="Example Image Caption 2" class="demo-img">
<span id="here"></span>
</div>
其他方法是選擇跨度并參考影像
$(".wrap span").text(function() {
return $(this).prev('img').attr('alt');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrap">
<img src="https://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RE4Y5jq?ver=ac72&q=90&m=6&h=201&w=358&b=#FFFFFFFF&l=f&o=t&aim=true" alt="Example Image Caption 1" class="demo-img">
<span id="here"></span>
</div>
<div class="wrap">
<img src="https://cdn-dynmedia-1.microsoft.com/is/image/microsoftcorp/gldn-M365-CP-Microsoft365-Commercial?wid=380&hei=213&fit=crop" alt="Example Image Caption 2" class="demo-img">
<span id="here"></span>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/489797.html
標籤:javascript jQuery
上一篇:在div中添加100個按鈕
