0

我有以下div:

<div class="test0 clickable">
   <div class="test1 clickable">
      <div class="test2 clickable">Click me</div>
   </div>
</div>

当我单击“test2”时,我希望将 div test2 从 dom 中删除,然后再从 div test1 中删除。它适用于除 IE8 和 IE9 之外的所有主流浏览器。

JavaScript 是:

$(".clickable").click(function(event){ 
  //if (some event condition)
     $(this).remove();
});

如何保证单击事件从 test2 冒泡到 test1 以便根据“事件”对象的条件删除两个 div?

4

3 回答 3

1

如果父项匹配选择器,请尝试显式删除父项:

$(".clickable").click(function(){ 
    $(this).remove();
    if ( $(this).parent().hasClass('clickable') ) $(this).parent().remove();
});
于 2013-05-06T18:17:01.497 回答
0

看起来 IE 在实现标准化事件流方面存在一些问题。但是,通过推迟节点删除,这应该很容易解决:

$(".clickable").click(function(event){
    var toremove = this;
    if (/*some event condition*/)
        setTimeout(function(){
            $(toremove).remove();
        }, 0);
});
于 2013-05-07T16:00:13.290 回答
0

使用 stopPropagation

$(".clickable").click(function(event){ 
      event.stopPropagation();
      $(this).remove();
});
于 2013-05-06T18:12:42.110 回答