2016-09-06 126 views
1

我有以下問題:我想選擇當前元素的所有子孫+孫。循環中嵌套的jquery選擇器當前元素

樣本HTML

<html> 
<head> 
    <title>Sample</title> 
</head> 
<body> 
    <div class="a"> 
    <div class="b"></div> 
    </div> 
    <div class="a"> 
    <div class="b"></div> 
    </div> 
</body> 
</html> 

我的JS循環經過每格A級 我想在這個循環和當前的div A級的只有B內的選擇B

$(".a").each(function(){ 
// SELECT div class B here and only the B of the current A 
}); 

爲什麼不能正常工作?

$(".a").each(function(){ 
    $(this).contents().filter('.b').each(function(){ 
     console.log("Test"); 
    }); 
    }); 
+0

https://api.jquery.com /最接近/ –

+0

'$('。a .b')。each(function(){$(this).closest('。b')。addClass('selected')。end()。addClass('selected' );});' – Tushar

回答

4

你的實現並沒有擔任.filter()在同一級別相匹配元件的方法。您需要使用.find()/.children(),因爲.b.a的後裔。

$(".a").each(function() { 
    $(this).find('.b').each(function() { 
     console.log("Test"); 
    }); 
}); 

OR,您可以直接使用Descendant Selector (「ancestor descendant」)

$(".a .b").each(function() { 
    console.log("Test"); 
}); 
0

你需要找到 「B」 的A內:

$(".a").each(function(){ 
    $(this).find('.b').each(function(){ 
    console.log("Test"); 
}); 
});