javascript - 在文档上点击而不是特定元素时显示警告
在我的HTML里
$(document).click(function(){
alert('Document Clicked');
})<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<button type='button'>CLICK [NO ALERT]</button>
<button type='button'>ME[NO ALERT]</button>
</body>在我的代码中,如果我点击按钮,如何防止警报弹出,但除按钮之外的任何东西都可以触发警报。
答案#1
你可以在那个特定的 <button> 上添加另一个 click 监听器,并阻止事件传播:
$(document).click(function(){
alert('Document Clicked');
})
$('.not-clickable').click(function(e) {
e.stopPropagation();
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<button type='button'>CLICK [NO ALERT]</button>
<button type='button' class="not-clickable">ME[NO ALERT]</button>
</body>另一个选项是检查被点击的元素是否是那个特定按钮:
$(document).click(function(e){
if (e.target.classList.contains('not-clickable')) {
return;
}
alert('Document Clicked');
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<button type='button'>CLICK [NO ALERT]</button>
<button type='button' class="not-clickable">ME[NO ALERT]</button>
</body>答案#2
试试
$("#SomeElementId").click(function(e) {
//do something
e.stopPropagation();
})