簡體   English   中英

jQuery取消綁定或特定父級內的單擊事件處理程序

[英]jquery unbind or off click event handler within specific parent

我有3個按鈕,所有按鈕都有單擊事件處理程序。

如果按鈕在特定的父項中,則該按鈕上不應有任何點擊事件。 但是,應該在該特定父級本身存在單擊事件。

在下面的代碼中,單擊.case2的按鈕時,我期望警報顯示“ case2 parent clicked”,但仍顯示警報“ button clicked”。

為什么會這樣呢? 我該如何糾正呢?

謝謝。

  $('.button').on('click', function (e) { alert('button clicked'); e.stopPropagation(); }); $('.case2') .off('click', '.button', function (e) { e.stopPropagation(); }) .on('click', function (e) { alert('case2 parent clicked'); e.stopPropagation(); }); 
 .case1, .case2, .case3 { margin:1em; padding: 1em; background-color: #0b97c4; width: 5em; height:2em; } .button { padding: 1em; background-color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="case1"> <div class="button"></div> </div> <div class="case2"> <div class="button"></div> </div> <div class="case3"> <div class="button"></div> </div> 

在選擇器中使用:not

 $('.button:not(.case2 .button)').on('click', function (e) { alert('button clicked'); e.stopPropagation(); }); $('.case2').on('click', function (e) { alert('case2 parent clicked'); e.stopPropagation(); }); 
 .case1, .case2, .case3 { margin:1em; padding: 1em; background-color: #0b97c4; width: 5em; height:2em; } .button { padding: 1em; background-color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="case1"> <div class="button"></div> </div> <div class="case2"> <div class="button"></div> </div> <div class="case3"> <div class="button"></div> </div> 

僅作為另一個示例,僅附加處理程序而不關閉它即可。

var buttons = $('.button');
buttons.not('.case2 .button').on('click', function(e) {
    alert('case first');
    e.stopPropagation();
  });
buttons.parents('.case2').on('click', function(e) {
  alert('case2 parent clicked');
  e.stopPropagation();
});

將“ .button”類添加到選擇器中:

$(".class2 .button").on("click",function(e){
    alert('button')
    e.stopPropagation()
 })

它應該首先火。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM