【发布时间】: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(),但我似乎无法让它正常工作。此外,我不能使用直接子代(或 >),因为后代可能位于其他非 .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 是对的。我会测试一下。