2016-11-14 55 views
0

我正在嘗試確定如何暫時禁用來自其他元素的點擊事件(或傳播?)。 所以當你點擊特定元素上的事件時,其他元素點擊事件不再被觸發。停止在不同元素上傳播

Simplified Example: 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 

<div id="World">World</div> 
<div id="Hello">Hello</div> 

    <script> 
    $(document).mousedown(function (e){ 
     if($('.there').length){ 
      $('.there').remove(); 
      console.log('removed there'); 
      //here is where I would need the '#World' click event to not fire 
     } 
    }); 

    $(document).on('click','#World',function(){ 
     console.log('World'); 
    }); 
    $(document).on('click','#Hello',function(){ 
     console.log('Hello'); 
     $(this).append('<div class="there">there</div>'); 
     console.log('added there'); 
    }); 
    </script> 

回答

0

事件是由元素觸發的......或者是您指定元素的集合。
和他們所有的孩子。

Events happen is this order

  1. 鼠標按下
  2. 鼠標鬆開
  3. 點擊

«當你點擊鼠標按下某個事件的特定元素上»
       真的會需要另一種方式來解釋它...

但我想我回答。

CodePen

$(document).on("mousedown",function(){ 
    console.log("mousedown"); 
}); 

$(document).on("click",function(){ 
    console.log("click"); 
}); 

$(document).on("mouseup",function(){ 
    console.log("mouseup"); 
}); 

//---- 

$(document).find("#main").on("mousedown click mouseup",function(e){ 
    e.stopPropagation(); 
    console.log("NOTHING...."); 
}); 

$(document).find("#okay input").on("mousedown click mouseup",function(e){ 
    e.stopPropagation(); 
    console.log("Just the OKAY"); 
}); 

只需點擊無處不在同時檢查控制檯。

細心的目光會看到如何禁用繼承。
它是如何「起泡」的。

0

我見過開發人員暫時從第二個元素中刪除事件,然後在必要時將其添加回去,但是我發現暫時禁用特定事件的最佳方法是向事件的處理程序添加代碼,以檢查某些事件一種狀態變量或類。我覺得我的措辭是很差,這裏有一個簡單的例子:

var buttonsToDisable = $('.mybuttons'), 
    disablerButton = $('#disabler'); 

buttonsToDisable.on('click',function(e) { 
    var ele = $(this); 
    if(!ele.is('.disable-click')) { 
     // some event handler logic here 
    }; 
}); 

// Toggle click-events on all buttons with the .mybuttons class when clicked 
disablerButton.on('click',function(e) { 
    if(!buttonsToDisable.is('.disable-click')) { 
     buttonsToDisable.addClass('disable-click'); 
    } else { 
     buttonsToDisable.removeClass('disable-click'); 
    }; 
}); 

如果您也想阻止mybuttons事件的傳播,則只需添加一個elseif聲明,並在那裏調用事件的stopPropagation()功能。

0

因爲#World是父母的孩子,那麼如果你先點擊#World,它的點擊事件將被觸發,然後是父母(div,body等),然後html。

如果您將在#World上停止傳播,則父母事件的點擊事件即使一次也不會觸發。

我認爲你需要檢查是否有低的.there點擊#World時可用。即

$(document).on('click','#World',function(){ 
    if ($('.there').length) { 
     return; // or return false; 
    } 

    else { 
     //code you want to execute 
     console.log('World'); 
    } 
});