javascript - stopPropagation() 不适用于委托(delegate)事件

标签 javascript jquery event-bubbling stoppropagation

我试图在其父级( .abb )获得点击时使用 $.toggle() 切换 .abb-bar 。但是每当 .abb-bar 获得点击时,它就会因为 事件冒泡 而自行切换。 e.stopPropagation() 应该可以解决问题,但它不起作用。可以做什么?

HTML

<span class="col-auto entry-ops abb">
    <i class="fa fa-bars"></i>
    <div class="list-group abb-bar">
        <button class="list-group-item list-group-item-action d-flex justify-content-center" data-user="nick">follow</button>
        <button class="list-group-item list-group-item-action d-flex justify-content-center complain">complain</button>
        <button class="list-group-item list-group-item-action d-flex justify-content-center show-entry-number" data-toggle="tooltip">'.$row['entry_id'].'</button>
    </div>
</span>

JS

$(document).on('click', '.abb', function( e ) {
    e.stopPropagation();
    $(this).children('.abb-bar').toggle();
});

最佳答案

您不应该在此处使用事件委托(delegate)。

当事件到达 document 时,只剩下一个元素可以传播到 (window)。它已经传播到 document,因此您无法对已经触发的元素追溯取消它。这就是事件委托(delegate)的本质...让事件一直向上冒泡,然后查看哪个元素发起了该事件。

只需在切换元素上设置点击事件,在子容器上取消点击事件即可。

// Set the click event handler on the toggle area
$('.abb').on('click', function( e ) {
    $('.abb-bar', this).toggle();
});

// Don't enable the click event on the child
$('.abb-bar').on('click', function( e ) {
    e.stopPropagation();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="col-auto entry-ops abb">
    <i class="fa fa-bars">Click to toggle</i>
    <div class="list-group abb-bar">
        <button class="list-group-item list-group-item-action d-flex justify-content-center" data-user="nick">follow</button>
        <button class="list-group-item list-group-item-action d-flex justify-content-center complain">complain</button>
        <button class="list-group-item list-group-item-action d-flex justify-content-center show-entry-number" data-toggle="tooltip">'.$row['entry_id'].'</button>
    </div>
</span>

关于javascript - stopPropagation() 不适用于委托(delegate)事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46383471/

相关文章:

javascript - CSS 3 Flexbox 模型宽度 jQuery

jquery - 如何使用更新的代码修改幻灯片来停止事件传播。

jquery - 如何使用 jquery 跳过冒泡阶段

javascript - 如何通过 javascript 在正确的 json 中制作我的数据

javascript - Metro 菜单 HTML/CSS/Jquery

javascript - <select> 标签中的列结构

JavaScript:对象的重组和数组

javascript - woocommerce 中带有砌体的无限滚动不起作用

jQuery:当底层元素使用 "event.stopPropagation()"设置单击事件时了解 "find()"

javascript - li slideDown 有效,但是当 slideUp 时它只是弹出而不滑动