2017-09-23 107 views
1

我試圖切換.abb-bar,使用$.toggle(),只要其父(.abb)得到一個點擊。但每當.abb-bar得到一個點擊,它會自己切換,因爲event-bubblinge.stopPropagation()應該解決問題,但它不起作用。可以做些什麼?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

stopPropagation將停止從點火那是它的父母......不是孩子的事件......但你坐在文件,所以點擊已經到達那裏。 – epascarello

+0

我沒有得到它爲什麼人們downvote別人的答案,不給理由 – krishnar

+0

@ krishnar你的答案可能是downvoted,因爲答案只包括代碼和解釋文本。嘗試添加一些關於您的代碼更改內容的解釋,以創建更好的收到答案。 –

回答

1

你不應該在這裏使用事件代表團。

當事件到達document時,它只有一個元素傳播到(window)。它已經傳播到document,所以你不能追溯取消它已經被觸發的元素。這是事件代表團的本質......讓事件一路向上,然後看看哪個元素髮起了事件。

您只需要在toggle元素上設置一個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>

+0

我沒有得到它爲什麼必須發送這個來切換 – krishnar

+0

@krishnar'abb-bar'是什麼需要被切換。 'this'(作爲選擇器的第二個參數)只是提供了可以找到它的地方的上下文。這是一種提高性能的方法,並且強烈建議在複雜的DOM結構中使用。這不是必需的。如果有多個'.abb-bar'元素,這將會被請求,因爲這將防止其他人切換。 –