簡體   English   中英

遍歷類元素數組並在jquery中選擇同級

[英]iterating through array of class elements and selecting sibling in jquery

我在html中有一個結構

 <div class="combo-wrapper" tabindex="0" style="display: inline-block; width: 120px; height: 23px;">
<div class="combo-button" style="width: 20px; height: 23px; display: inline-block;"></div>
<div class="combo-selected" style="width: 100px; height: 23px; display: inline-block;">Pending For Upload L2-GM</div>
</div>

在同級中,我有一個下拉菜單

<select class="bydd">
<option value="">Select</option>
<option value="H">Hold</option>
<option value="D">Delete</option>
</select>

當我嘗試設置標題時

$(".combo-wrapper").each(function (i) {

        $('.combo-wrapper')[i].attr("title", $('.combo-wrapper')[i].siblings(".bydd option:selected").text());

    });

引發未定義的錯誤

$('.combo-wrapper')[0].siblings()本身不會在控制台中引發函數錯誤

當您通過索引從jQuery對象檢索值時,實際上是在獲取底層的DOMElement而不是jQuery對象,因此在嘗試獲取attr時會出現undefined function錯誤。

要通過索引獲取jQuery對象,您需要使用eq()方法:

$('.combo-wrapper').eq(i).attr("title", $('.combo-wrapper').eq(i).siblings(".bydd option:selected").text());

或者,您可以使用:eq選擇器:

$('.combo-wrapper:eq(' + i + ')').attr("title", $('.combo-wrapper:eq(' + i + ')').siblings(".bydd option:selected").text());

因為$('.combo-wrapper')[0]返回一個dom元素引用,該引用沒有jQuery相關的方法。

您可以使用this (它也是一個dom元素引用,而不是jQuery包裝器)來引用每個循環中的當前元素,然后將其包裝在jQuery中以在其上使用jQuery方法

$(".combo-wrapper").each(function (i) {

    $(this).attr("title", $(this).siblings(".bydd").find("option:selected").text());

});

另一種方法是

$(".combo-wrapper").attr("title", function () {
    return $(this).siblings(".bydd").find("option:selected").text()
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM