event.preventDefault()和多个事件

时间:2011-04-11 11:42:03

标签: javascript jquery events

在我开始编写大量不起作用的代码之前,我想我会问这个问题。

event.preventDefault()只取消点击事件的默认操作吗?

理论上我应该能够将jQuery中的多个click事件处理程序绑定到给定目标,以执行不同的操作,如Ajax帖子和Google跟踪。

我错了吗?

1 个答案:

答案 0 :(得分:25)

  

event.preventDefault()只取消点击事件的默认操作吗?

取消浏览器对该事件的默认操作(不仅仅是click事件)(W3C docsjQuery docs)。例如,在submit事件的形式中,它会阻止浏览器提交表单。它不会阻止你在代码中做的任何事情,也不会停止冒泡;这是(W3C docsjQuery docs)的stopPropagation

因此,假设您在div中有一个链接,并且链接和click上都挂有div个事件。如果链接的事件处理程序调用{​​{1}},浏览器将不会执行其默认操作(在链接之后),但事件继续将DOM冒泡到链接的父元素preventDefault,并且所以你也会在那里的div处理程序上看到这个事件。您在任一处理程序中的代码中执行的任何操作都不会受到您的调用click的影响。

在下面的评论中,您询问相同元素上的多个处理程序。 preventDefaultpreventDefault都没有影响到它们,它们仍会被解雇...除非你使用stopImmediatePropagation,它告诉jQuery阻止事件死亡(但不能阻止)浏览器的默认操作)。

我应该通过说,如果从事件处理程序返回stopPropagation,那么告诉jQuery阻止默认的停止冒泡。这就像调用falsepreventDefault一样。当您的事件处理程序完全控制事件时,它是一个方便的快捷方式。

所以,鉴于这个HTML:

stopPropagation

示例1:

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

示例2:

// 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();
});

示例3 (您很少会看到这一点):

// 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();
});

示例4:

// 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();
});