javascript - 如何在jQuery中阻止父元素的点击事件?

标签 javascript jquery html css

我正在使用 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/

相关文章:

jquery - 单击时绝对定位按钮移动

php - 如何在 jQuery 加载时传递 PHP 变量?

html - 为什么在 style 标签中经常有一个 &lt;!-- ?

javascript - 如何在 JavaScript 中创建 aes-256 加密

javascript - 缺乏对 AJAX 预加载的理解(附示例)

javascript - this.textInput.focus 不是函数 - React

html - 如何使 &lt;input&gt; 的实际大小为 ="..."?

javascript - 将数据传递给 Jison 解析器

javascript - 为什么 setInterval 会无限循环

html - 如何让 SVG 中的字体显示在网页中?