首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >stopPropagation()不适用于委托事件

stopPropagation()不适用于委托事件
EN

Stack Overflow用户
提问于 2017-09-23 19:26:12
回答 1查看 1.9K关注 0票数 2

我正在尝试切换.abb-bar,只要它的父( .abb )被单击,就使用$.toggle()。但是每当.abb-bar被点击时,它就会因为event-bubbling而自动切换。e.stopPropagation()应该解决这个问题,但它不起作用。我们能做些什么?

HTML

代码语言:javascript
复制
<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

代码语言:javascript
复制
$(document).on('click', '.abb', function( e ) {
    e.stopPropagation();
    $(this).children('.abb-bar').toggle();
});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-09-23 19:49:12

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

当事件到达document时,只有一个要传播到(window)的元素。它已经传播到document,所以不能追溯取消它已经触发的元素。这就是事件授权的本质..。让事件始终保持泡沫状态,然后查看是哪个元素发起了事件。

您只需要在“切换”元素上设置一个单击事件,并取消子容器上的“单击”事件。

代码语言:javascript
复制
// 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();
});
代码语言:javascript
复制
<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>

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46383471

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档