jQuery/JavaScript:选择第一个“层"仅儿童 [英] jQuery/JavaScript: selecting first "layer" of children only

查看:99
本文介绍了jQuery/JavaScript:选择第一个“层"仅儿童的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图仅选择给定类型的子元素的第一个层",而不是嵌套在另一个限定元素内的元素.例如.在:

I'm trying to select only the first "layer" of children elements of a given type, but not elements nested inside another qualifying element. E.g. in:

<div id='top'>
  <div id="s1" class="special">
    <div id="s2" class="special"></div>
  </div>
  <div>
    <div id="s3" class="special"></div>
  </div>
</div>

我想找到#s1和#s3,但不找到#s2,类似$('#top').find('.special:not_nested'). jQuery有可能吗? XPATH?

I'd like to find #s1 and #s3, but not #s2, with something like $('#top').find('.special:not_nested'). Is it possible with jQuery? XPATH?

我想到了像expr [':'].not_nested之类的jQuery自定义过滤器,但是由于可能存在其他其他.special类在#top的父链中更远.

I thought about jQuery custom filters like expr[':'].not_nested, but can't figure out how to take into account the top parent ($('#top') in this case), because there may be other .special classes further up in the parent chain of #top.

[edit]我现在应该提一下,我正在递归调用$ .fn.children(),我认为这不是很有效.

[edit] I should mention right now I'm resorting to a recursive call to $.fn.children() which I think is not very efficient.

[edit2]经过测试的工作代码:

[edit2] tested working code:

    var node = $('#top'),
    result = (node.find('.special').filter(function(){
       return !($(this).parent().closest(".special", node).length);
    }));

但是,如果"#top"本身具有.special类,则此方法不起作用.所以也许是这样:

However, this doesn't work if "#top" has .special class itself. So maybe this:

var node = $('#top'),
result= node.find('.special').filter(function(){
   var parent = $(this).parent().closest(".special", node);
   return !parent.length || parent.is(node);
});

推荐答案

另一种选择是使用.children()代替.find(),但其结果与idrumgood的解决方案相同.

Another option is to use .children() in place of .find(), but it will have the same result as idrumgood's solution.

$('#top').children('.special')

我刚刚意识到#s3的嵌套,这可能适用于这种情况:

i just realized the nesting of #s3, this may work for that situation:

$('#top').find('.special').filter(function(){
  return $(this).closest('.special').length === 0;
}).doSomething()

Edit2:在这里继续:

here ya go:

$('#top').find('.special').filter(function(){
   return !$(this).parent().closest(".special").closest("#top").length;
}).doSomething;

这篇关于jQuery/JavaScript:选择第一个“层"仅儿童的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆