循环中嵌套的jquery选择器当前元素

问题描述:

我有以下问题:我想选择当前元素的所有子孙+孙。循环中嵌套的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

你的实现并没有担任.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"); 
}); 

你需要找到 “B” 的A内:

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