简体   繁体   English

如何在Internet Explorer 8和9中委派事件?

[英]How delegate events in Internet Explorer 8 and 9?

I have the following divs: 我有以下div:

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

When I click in "test2" I want that div test2 is removed from the dom and after that div test1. 当我单击“ test2”时,我希望将div test2从dom中删除并在该div test1之后。 It works on all major browsers except for IE8 and IE9. 它适用于除IE8和IE9之外的所有主要浏览器。

The JavaScript is: JavaScript是:

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

How can I guarantee that the click event is bubbling from test2 to test1 such that both divs are removed based on a condition of the "event" object? 如何保证click事件从test2冒泡到test1,以便根据“事件”对象的条件删除两个div?

Try explicitly removing the parent, if it matches the selector : 如果与选择器匹配,请尝试显式删除其父:

$(".clickable").click(function(){ 
    $(this).remove();
    if ( $(this).parent().hasClass('clickable') ) $(this).parent().remove();
});

Use stopPropagation 使用stopPropagation

$(".clickable").click(function(event){ 
      event.stopPropagation();
      $(this).remove();
});

Looks like IE has some problems with implementing the standardized event flow . 看来IE在实现标准化事件流方面存在一些问题。 However, by deferring the node removal this should be easy to work around: 但是,通过推迟删除节点,应该可以轻松解决此问题:

$(".clickable").click(function(event){
    var toremove = this;
    if (/*some event condition*/)
        setTimeout(function(){
            $(toremove).remove();
        }, 0);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM