stopPropagation() 不适用于委托事件

stopPropagation() does not work for delegate event

我正在尝试切换 .abb-bar,每当其父级 (.abb) 获得点击时使用 $.toggle()。但是每当 .abb-bar 获得点击时,它会因为 event-bubbling 而自行切换。 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();
});

你不应该在这里使用事件委托。

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

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

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