2012-03-30 94 views
1

檢查下面的代碼:DOM Level 0事件:如何防止外部點擊發射?

​<div onclick="alert('Hi, from outer div!');"> 
    <button onclick="alert('Hi, from button!');">Tha button</button>, Click me! 
</div>​​​​ 

是否有辦法防止外DIV從發射一個onclick當我點擊按鈕?任何想法如何取消DOM級別0事件?

注意:我不能使用jQuery。它需要在Chrome,FireFox,IE6-9上運行。

+1

你可能想[初級](http://www.quirksmode.org/js/events_order.html)爲初學者 – Joseph 2012-03-30 09:42:18

+0

可能的重複[防止父容器點擊事件從點擊超鏈接時發射](http://stackoverflow.com/questions/1997084/prevent-parent-container-click-event-from-firing-when-hyperlink-clicked)...看看最高的投票答案,而不是(如果你不使用jQuery)。 – 2012-03-30 09:42:47

+0

@FelixKling,我正在使用沒有處理程序的1級dom事件,這可能是一個很大的區別... – 2012-03-30 09:43:43

回答

5

是的。在大多數標準的瀏覽器,你在事件對象上調用stopPropagationlive example | source):

​<div onclick="alert('Hi, from outer div!');"> 
    <button onclick="alert('Hi, from button!'); event.stopPropagation();">Tha button</button>, Click me! 
</div>​​​​ 

在IE瀏覽器的較舊的副本,您必須將cancelBubble屬性設置爲true代替:

​<div onclick="alert('Hi, from outer div!');"> 
    <button onclick="alert('Hi, from button!'); event.cancelBubble = false;">Tha button</button>, Click me! 
</div>​​​​ 

。 ..這意味着爲了廣泛的兼容性,你必須測試你正在處理哪個,哪個變得醜陋(live example | source):

​<div onclick="alert('Hi, from outer div!');"> 
    <button onclick="alert('Hi, from button!'); if (event.stopPropagation) { event.stopPropagation(); } else { event.cancelBubble = true; }">Tha button</button>, Click me! 
</div>​​​​ 

這些各種各樣的差別,爲什麼我總是建議移動從舊DOM0式處理掉,並使用一個體面的JavaScript庫,例如jQueryPrototypeYUIClosure,或any of several others。這些平滑的瀏覽器之間的差異,並提供了大量的實用功能。

例如,使用jQuery,這個HTML:

​<div id="theDiv"> 
    <button id="theButton">Tha button</button>, Click me! 
</div>​​​​ 

...這腳本(live example | source):

$("#theDiv").click(function() { 
    alert('Hi, from outer div!'); 
}); 
$("#theButton").click(function(event) { 
    alert('Hi, from button!'); 
    event.stopPropagation(); // Even on IE, jQuery provides this 
}); 

或經常使用jQuery,你看人家只是做return false;在其事件處理程序中。處理器中的return false;,jQuery中的,會做兩件事:停止傳播,並阻止事件可能具有的任何默認操作(例如,在鏈接上的點擊處理程序中)。 stopPropgation不會阻止默認設置。

但這並不意味着是jQuery的廣告(雖然它是一個非常好的庫)。關閉,YUI,Prototype和其他所有其他類似的功能讓你不用擔心瀏覽器的這些不兼容問題。

+0

「舊版本」也是IE6? – 2012-03-30 09:46:41

+1

@Kees:在IE9之前的任何東西。 – 2012-03-30 09:47:53

+0

似乎可以在IE8中工作:P – 2012-03-30 09:48:24

0
<div onclick="alert('Hi, from outer div!');"> 
    <button onclick="event.stopPropagation(); alert('Hi, from button!');">Tha button</button>, Click me! 
</div>​ 

我添加的是一個event.stopPropagation(); 這樣做是停止發生冒泡

+0

'事件'是否適用於所有瀏覽器? – 2012-03-30 09:44:07

+0

@ KeesC.Bakker:在這種情況下,是的;但'event.stopPropgation()'不會,老版本的IE沒有它。 – 2012-03-30 09:46:12