我正在使用 jQuery
开发一个网页。在此网页中,有一个 div 标签,其中包含一个 p
和一个 button
标签。
HTML
代码如下:
<div class="container">
<div id="attribute" style="border:solid;border-width:2px;border-color:#ccc">
<p id="cell-content" style="display:inline">Id</p>
<button id="remark-view" class="btn btn-primary">Detail</button>
</div>
</div>
对应的JavaScript
代码如下:
$(document).ready(function(){
$("#attribute").on('click', function(){
console.log("click on the div attribute");
});
$("#attribute").on('dblclick', function(){
console.log("double click on the div attribute");
});
$("#remark-view").on('click', function(){
console.log("click on the button remark-view");
});
});
如代码所示,外部 div 有一个 p 和 button 子元素,外部 div 元素监听单击和双击事件,而内部 Button 元素监听单击事件。
当我在浏览器中运行代码并单击按钮时,控制台显示外部 div 和内部按钮元素的单击函数都被调用,这违背了我的目的:只应该调用内部按钮的单击函数在这种情况下打电话。因此,有没有办法阻止父元素(在本例中为外部 div 元素)的单击事件。换句话说,有没有办法在子元素处理完单击事件后停止将单击事件传递给父元素?
提前谢谢您!
最佳答案
stopPropagation 函数将阻止事件在 DOM 中冒泡。
$("#remark-view").on('click', function(event){
console.log("click on the button remark-view");
event.stopPropagation()
});
来自 jQuery 文档
Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
关于javascript - 如何在jQuery中阻止父元素的点击事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45626636/