如何防止点击传播

时间:2013-09-11 04:12:31

标签: javascript jquery

我有以下div并单击侦听器:

  $('.right-col .modal-container').live('click',function(e) {
       $(this).remove();
       $('.right-col .modal-backdrop').remove();
  });


<div class="modal-container">
    ....some other buttons and html elements inside
</div>

问题在于,当我单击此模态容器元素内的按钮时,它还会触发.modal-container中的单击功能。我该如何避免这种级联?

3 个答案:

答案 0 :(得分:0)

在谷歌中写下您的问题标题后,这里是第一个链接:http://api.jquery.com/event.stopPropagation/

以下是如何使用它:

$('.right-col .modal-container').on('click',function(e) {
    $(this).remove();
    $('.right-col .modal-backdrop').remove();
}).find('button').click(function(e){ //guessing you have a <button> in the div
     e.stopPropagation();
});

答案 1 :(得分:0)

  

如何确保此点击事件不是来自a   传播点击,但直接点击此div

使用if (this == e.target){

$('.right-col .modal-container').on('click',function(e) {
    if (this == e.target){
       $(this).remove();
       $('.right-col .modal-backdrop').remove();
    }
});

e.target 您直接点击 的元素,而不是e.currentTarget,它是传播中的当前元素。这也适用于 事件捕获 ,因为事件捕获:事件在到达被点击的元素之前首先在容器上触发。

为了获得性能优势,您还应该按照@ Karl-AndréGagnon的建议尝试stopPropagation,以便在 事件冒泡 的情况下停止事件传播

Difference between event capturing and event bubbling

答案 2 :(得分:0)

如果您不希望div.modal-container成为目标,则可以在<button>上注册点击事件。假设您将按钮的类名称设为.modal-container,则可以尝试以下操作:

$("button.modal-container").live('click', function(e){
    // your button specific actions here
    // ...

    $(e.target).parents(".modal-container").first().remove();
});
相关问题