[英]JQuery: When .each over children with parents with different ID's, the first Parent's ID persists
總而言之,我已盡力解決這個問題,雖然我發現可能的例子要復雜得多,似乎我是唯一一個有這個問題的人,所以我來找你幫助,或者只是一個解釋。
在下面的代碼中,我希望連續看到三個警報,tab-1,tab-2和tab-3,但我會看到tab-1的三個警報。 為什么這個和可能的解決方案可以達到預期的效果?
感謝您的時間和幫助。
HTML
<div id="tab-1">
<span class="test"></span>
</div>
<div id="tab-2">
<span class="test"></span>
</div>
<div id="tab-3">
<span class="test"></span>
</div>
jQuery
$('.test').each(function() {
alert($('.test').parent().attr("id"));
});
你的每個語法都有點偏差。
$(".test").each(function(index, element) {
alert($(element).parent().attr("id"));
});
這使用您正在進行的迭代,而不是再次查詢每個測試類並使用第一個測試類。
因為您要查詢$('.test')
而不是使用.each()
循環中的項目,所以將其更改為
$('.test').each(function() {
alert($(this).parent().attr("id"));
});
見這里: http : //jsfiddle.net/gLh5z/
您還可以使用function(idx, elem)
然后使用$(elem)
而不是$(this)
因為函數將作為前兩個參數傳遞索引和元素。
雖然你的代碼很接近,但它並不完全正確。 你應該使用:
$('.test').each(function() {
alert($(this).parent().attr("id"));
});
您遇到的問題是您在each()
每次迭代中重新選擇數組,而jQuery將只返回返回的數組的第一個元素的屬性。
參考文獻:
each()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.