use*_*127 5 jquery nested selector
我试图仅选择给定类型的子元素的第一“层”,而不选择嵌套在另一个限定元素内的元素。例如在:
<div id='top'>
<div id="s1" class="special">
<div id="s2" class="special"></div>
</div>
<div>
<div id="s3" class="special"></div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
我想找到#s1和#s3,但不是#s2,比如$('#top').find('.special:not_nested')。用 jQuery 可以吗?X路径?
我考虑过像 expr[':'].not_nested 这样的 jQuery 自定义过滤器,但无法弄清楚如何考虑顶级父级(在本例中为 $('#top')),因为可能还有其他 .special #top 父链中更上层的类。
[编辑] 我应该提到现在我正在诉诸对 $.fn.children() 的递归调用,我认为这不是很有效。
[edit2]测试工作代码:
var node = $('#top'),
result = (node.find('.special').filter(function(){
return !($(this).parent().closest(".special", node).length);
}));
Run Code Online (Sandbox Code Playgroud)
但是,如果“#top”本身具有 .special 类,则此方法不起作用。所以也许是这样的:
var node = $('#top'),
result= node.find('.special').filter(function(){
var parent = $(this).parent().closest(".special", node);
return !parent.length || parent.is(node);
});
Run Code Online (Sandbox Code Playgroud)
另一种选择是使用.children()代替.find(),但它的结果与 idrumgood 的解决方案相同。
$('#top').children('.special')
Run Code Online (Sandbox Code Playgroud)
编辑:我刚刚意识到 的嵌套#s3,这可能适用于这种情况:
$('#top').find('.special').filter(function(){
return $(this).closest('.special').length === 0;
}).doSomething()
Run Code Online (Sandbox Code Playgroud)
编辑2:开始吧:
$('#top').find('.special').filter(function(){
return !$(this).parent().closest(".special").closest("#top").length;
}).doSomething;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4193 次 |
| 最近记录: |