Jquery选择器:not inside child div

标签 jquery css

我希望能够使用 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) .

.closest() method:

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.

Updated Example

$(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/

相关文章:

javascript - 如何将幻灯片范围插入mysql?

javascript - 更改整个页面内容的文本字体大小

css - 我应该如何将图像附加到边框底部?

javascript - Bootstrap Typeahead 转义?

javascript - 再次单击或单击其他位置时如何关闭 Bootstrap 弹出窗口

javascript - 在javascript中重新排序字符串

javascript - 如何在 CSS3 中保持动画之间的状态?

html - css 跨浏览器差异

css - 媒体查询 : How to NOT target Ipad

javascript - 如何限制除 jpg png 或 gif 之外的图像大小和扩展名