2013-05-06 62 views
0

我有以下的div:如何在Internet Explorer 8和9中委託事件?

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

當我點擊「測試2」我想該div test2的從DOM和之後的DIV test1的去除。它適用於除IE8和IE9以外的所有主流瀏覽器。

的JavaScript是:

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

我如何能保證點擊事件從TEST2浮上TEST1,使得兩個div的是基於「事件」的條件移除的對象?

+0

因此,在IE中'test1'不會被刪除? – dfsq 2013-05-06 18:12:21

+0

可能是IE不遵循標準事件模型的另一種情況... – Bergi 2013-05-06 18:17:26

+0

請注意,它適用於IE9,但不適用於IE8。 http://jsfiddle.net/Ttn8g/4/(確保控制檯已打開) – 2013-05-06 18:25:55

回答

0

使用stopPropagation

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

這與他想要的相反嗎? – Barmar 2013-05-06 18:14:02

+0

他想先刪除孩子,然後給父母rt ..? – Sarath 2013-05-06 18:15:15

+0

這就是他寫的:_guarantee ...兩個div都被刪除了_ – Barmar 2013-05-06 18:16:38

1

嘗試刪除明確家長,如果選擇匹配:

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

或'$(this).parents(「。clickable」)。remove()'因爲所有父母都是.clickable最終會冒泡到假設什麼都不停它在路上。 – 2013-05-06 18:23:06

+0

我更新了我的帖子。除去div應基於某些事件條件,例如基於鼠標位置。所以我需要每個clickable都可以從click事件中接收事件對象。 – confile 2013-05-06 18:39:06

+0

鼠標位置是否從元素變爲元素? – adeneo 2013-05-06 19:01:37

0

看起來像IE瀏覽器有一些問題,實施standardized event flow。但是,通過推遲刪除節點,這應該很容易解決:

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