【问题标题】:jQuery - select class not contained in another class [duplicate]jQuery - 选择不包含在另一个类中的类[重复]
【发布时间】:2010-10-15 04:36:54
【问题描述】:

可能重复:
jQuery filtering selector to remove nested elements matching pattern.

我有一个组层次结构。比如:

<div class="group">
    <span class="child"></span>
    <div class="group">
        <span class="child"></span>
        <span class="child"></span>
        <span class="child"></span>
    </div>
    <span class="child"></span>
    <span class="child"></span>
    <div>This child is farther down <span class="child"></span></div>
</div>

如何在不选择任何子组的孩子的情况下选择每个组中的孩子?

$(".group").each(function() {
    // Wrong, click fires twice (the 1st level group selects 2nd level children)
    var children = $(this).children(".child");

    // Wrong, click fires twice
    children = $(this).children(":not(.group) .child");

    // How can I properly do this??

    children.click(function() {
        alert("children.click");
    });
});

我也尝试过find() 而不是children(),但我似乎无法让它正常工作。此外,我不能使用直接子代(或 &gt;),因为后代可能位于其他非 .gorup HTML 标记内(即向下几个 DOM 级别)。

【问题讨论】:

  • 嗯,我在 jsfiddle 中尝试过,点击没有触发两次......但无论如何,您可能希望使用 event.stopPropagation() 来防止事件冒泡。
  • 孩子可以往下几层是什么意思?无论结构如何, .group > .child 都会根据 DOM 布局选择您需要的分组。
  • 孩子!= 后代。 儿童只能下一层...
  • 我很确定这是stackoverflow.com/questions/3096098/… 的骗子——基本上可以归结为var $g = $(this), children = $g.find('.child').not($g.find('.group .child'));,如this fiddle 所示。另外,不要忘记 click 事件将传播到父 .child 除非您 return false
  • 我认为@gnarf 是对的。我会测试一下。

标签: jquery jquery-selectors


【解决方案1】:

如果.child 始终是其组的直接后代,则&gt; 选择器将起作用,如上所述。否则,您可以使用函数过滤设置

var group = this;
$(group).find('.child').filter(function() {
    // check if current element belongs to our group
    return $(this).closest('.group')[0] == group;
})

An example

【讨论】:

  • 我认为 gnarf 和你都是对的。我认为你的会更快,因为它只需要向上树几个节点,但它确实必须为每个孩子都这样做,所以我不完全确定。这是我正在寻找的更接近的版本:jsfiddle.net/KxnTZ/2
  • @Nelson Version with not 也处理每个孩子,所以我认为他们应该有相当的速度。虽然,这取决于 jquery 中集合子结构的有效性:如果 a.not(b) 意味着 a 的每个元素都与 b 的每个元素进行比较,那会很糟糕。
  • 所以我真正的问题是我实际上需要在跨度内选择一个复选框。所以我有类似$(group).find(".child").filter(...).find(":checkbox")的东西。当然,最后一次发现并没有停留在边界内,因为我们之前已经过滤过了。您的示例(有效)帮助我找到了这个错误。
  • .find().not(.find()) 似乎更快:jsperf.com/selector-test-find-not
  • @gnarf 谢谢!应该为该网站添加书签。
【解决方案2】:

如果您只想要一个组的直接子代,您可以尝试以下方法:

$('.group > .child').click(function(){
    alert('You clicked on: '+$(this).text());
});

请参阅jQuery: child-selector 上的文档

编辑:否则您可能想查看 gnarf 发布的 duplicate question

【讨论】:

  • 我添加了一些您可能错过的信息。孩子可能在其他非 .group HTML 标记内。
【解决方案3】:

试试这个,它的可读性也很强:

$(".group").each(function() {
  var allChilds = $(this).find('.child');
  var subChilds = $(this).find('.group .child');

  var firstChilds = allChilds.not(subChilds);
  firstChilds.css({ color: 'red' });
});

【讨论】:

    猜你喜欢
    • 2016-05-04
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-05
    • 2020-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多