简体   繁体   中英

How delegate events in Internet Explorer 8 and 9?

I have the following divs:

<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. It works on all major browsers except for IE8 and IE9.

The JavaScript is:

$(".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?

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

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

Looks like IE has some problems with implementing the standardized event flow . 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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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