我希望能够使用 jquery 在 body
标记上绑定(bind)点击事件,但不能在 class='noclick' 的子 div 内绑定(bind)点击事件。
<div>
<div>you can click here</div>
<br><br><br>
<div class='noclick'>NO ALERT</div>
</div>
这不起作用
$("body:not(.noclick)").on('click', function (e) {
alert("clicked")
});
这是一个JSFiddle
最佳答案
在您的示例中, :not()
pseudo class没有做任何事情。
jQuery 选择器 $("body:not(.noclick)")
将选择body
不具有类 .noclick
的元素。在您的示例中,body
元素没有 .noclick
类,这意味着它将被选中,并且单击事件将冒泡到 body
无论元素如何,该函数都会被触发。
您可以通过检索 target
property来访问对单击元素的引用。 event
的对象(在本例中为 e.target
)。
从那里,您可以使用 .closest()
method确定单击的元素是否具有类 .noclick
的祖先或(如果当前元素的类为 .noclick
) .
For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
$(document).on('click', function (e) {
if (!$(e.target).closest('.noclick').length) {
alert('Alert');
}
});
关于Jquery选择器:not inside child div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31594658/