event.preventDefault()
仅取消点击事件的默认操作不是吗?
它取消浏览器对事件的默认操作(不仅仅是click
事件) (W3C docs http://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113/events.html#Events-Event-preventDefault, jQuery 文档 http://api.jquery.com/event.preventDefault/)。例如,在形式中submit
事件,它阻止浏览器提交表单。它不会停止您在代码中所做的任何事情,也不会停止冒泡;就是这样stopPropagation
是为了(W3C docs http://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113/events.html#Events-Event-stopPropagation, jQuery 文档 http://api.jquery.com/event.stopPropagation/).
假设您有一个链接div
,并且你有click
事件同时挂在链接和div
。如果链接的事件处理程序调用preventDefault
,浏览器不会执行其默认操作(跟随链接),但该事件继续将 DOM 向上冒泡到链接的父元素,即div
,这样您就会在您的click
处理程序也在那里。您在任一处理程序中的代码中执行的任何操作都不会受到您的调用的影响preventDefault
.
在下面的评论中,您询问了有关多个处理程序的问题same元素。两者都不preventDefault
nor stopPropagation
影响那些,他们仍然会被解雇......除非你使用stopImmediatePropagation http://api.jquery.com/event.stopImmediatePropagation/,它告诉 jQuery 停止事件(但不会阻止浏览器的默认操作)。
我可能应该说如果你回来false
从你的事件处理程序中,它告诉 jQuery 阻止默认的and停止冒泡。就像打电话一样preventDefault
and stopPropagation
。当您的事件处理程序完全控制事件时,这是一种方便的快捷方式。
所以,给定这个 HTML:
<div id='foo'><a href='http://stackoverflow.com'>Q&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;
});