我正在尝试使用.abb-bar
切换$.toggle()
,只要其父级(.abb
)获得点击即可。但是只要.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();
});
答案 0 :(得分:2)
您不应该在此处使用事件委派。
当事件到达document
时,只有一个元素可以传播到(window
)。它已经传播到document
,因此您无法追溯它已经触发的元素。这是事件委托的本质......让事件一直冒泡,然后看看哪个元素发起了事件。
您只需要在切换元素上设置click事件并取消子容器上的click事件。
// 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>