2011-04-11 22 views
4

在我開始寫大量不工作的代碼之前,我想我會問這個問題。event.preventDefault()和多個事件

event.preventDefault()只取消點擊事件的默認動作不是嗎?

理論上我應該可以將jQuery中的多個單擊事件處理程序綁定到給定的目標,以執行不同的操作,如Ajax帖子和Google跟蹤。

我錯了嗎?

+0

像???也許答案是肯定的! – 2011-04-11 11:44:03

+0

它取消事件處理程序執行的事件的默認操作。 – 2011-04-11 11:47:50

+0

@diEcho:'stop'是Prototype,而不是jQuery(在jQuery中,['stop'](http://api.jquery.com/stop/)涉及動畫,而不是事件)。並且['end'](http://api.jquery.com/end/)涉及匹配的集合過濾,而不是事件。 – 2011-04-11 11:51:33

回答

23

event.preventDefault()只取消點擊事件的默認動作不是嗎?

它取消瀏覽器的默認事件(而不僅僅是click事件)(W3C docsjQuery docs)的作用。因此,例如,以submit事件的形式,它會阻止瀏覽器提交表單。它不會阻止你在代碼中做的任何事情,也不會阻止冒泡;這就是stopPropagation的用途(W3C docs,jQuery docs)。

所以假設您在div中有一個鏈接,並且您在鏈接和div上都掛鉤了click事件。如果鏈接的事件處理程序調用preventDefault,則瀏覽器將不會執行其默認操作(在鏈接之後),但該事件會繼續將DOM向上冒泡到鏈接的父元素div,因此您將看到事件那裏也有你的click處理程序。您在任何處理程序中執行的任何代碼操作都不會受到您致電preventDefault的影響。

在您的評論下面,你問了關於相同元素的多個處理程序。 preventDefaultstopPropagation都不會影響到這些,但它們仍然會被解僱......除非您使用stopImmediatePropagation,它告訴jQuery停止事件在其軌道中死去(但不阻止瀏覽器的默認操作)。

我應該說,如果你從你的事件處理函數返回false,那告訴jQuery阻止默認的停止冒泡。這就像撥打preventDefaultstopPropagation。當您的事件處理程序正在全面控制事件時,這是一個方便的快捷方式。

因此,鑑於此HTML:

<div id='foo'><a href='http://stackoverflow.com'>Q&amp;A</a></div> 

實施例1:

// Here we're preventing the default but not stopping bubbling, 
// and so the browser won't follow the link, but the div will 
// see the event and the alert will fire. 
$("#foo").click(function() { 
    alert("foo clicked"); 
}); 
$("#foo a").click(function(event) { 
    event.preventDefault(); 
}); 

實施例2:

// Here we're stopping propagation and not preventing the default; 
// the browser will follow the link and the div will not be given 
// a chance to process the event (no alert, and more to the point, 
// code in the div's handler can't prevent the default) 
$("#foo").click(function() { 
    alert("foo clicked"); 
}); 
$("#foo a").click(function(event) { 
    event.stopPropagation(); 
}); 

實施例3(喲日子會把只有很少看到此):

// Here we're doing both, and so the browser doesn't follow the 
// link and the div doesn't see the event (no alert). 
$("#foo").click(function() { 
    alert("foo clicked"); 
}); 
$("#foo a").click(function(event) { 
    event.preventDefault(); 
    event.stopPropagation(); 
}); 

實施例4:

// Shorter version of Example 3, exactly the same effect 
$("#foo").click(function() { 
    alert("foo clicked"); 
}); 
$("#foo a").click(function() { 
    return false; 
}); 
+0

J:對不起,我的意思是所有事件不只是點擊。我今天還沒有醒來....所以只是爲了澄清。我可以將一個點擊事件綁定到一個鏈接來執行一個投票或類似的事情,但是我可以單獨另一個綁定到該鏈接的點擊事件來進行跟蹤而不會相互干擾? – 2011-04-11 12:01:23

+0

@James:沒錯,其他事件處理程序不受影響,只是瀏覽器的默認操作。 [例子](http://jsbin.com/uwidu3/)有**是一種告訴jQuery停止事件的方法:['stopImmediatePropagation'](http://api.jquery.com /event.stopImmediatePropagation/)。如果你使用*那*,你的處理程序就會互相干擾:[例子](http://jsbin.com/uwidu3/2/) – 2011-04-11 12:05:56

+0

J:哇......這是一個答案!非常感謝。 – 2011-04-11 12:06:56

相關問題