我有以下问题:我想选择当前元素的所有子代和孙代。
示例 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 循环遍历每个 div 类 A。 我想在此循环中选择 B,并且仅选择当前 div 类 A 的 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");
});
});
最佳答案
您的实现无效,因为方法 .filter()
匹配同一级别的元素。您需要使用 .find()
/.children()
因为 .b
是 .a
的后代。
$(".a").each(function() {
$(this).find('.b').each(function() {
console.log("Test");
});
});
或者,你可以直接使用Descendant Selector (“ancestor descendant”)
$(".a .b").each(function() {
console.log("Test");
});
关于javascript - 循环中的嵌套 Jquery 选择器当前元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39349132/