event.preventDefault()和多个事件

Jam*_*uth 7 javascript jquery events

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

event.preventDefault() 只取消click事件的默认动作不是吗?

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

我错了吗?

T.J*_*der 26

event.preventDefault() 只取消click事件的默认动作不是吗?

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

所以说你有一个链接div,你有click链接和链接的事件div.如果链接的事件处理程序调用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>
Run Code Online (Sandbox Code Playgroud)

例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();
});
Run Code Online (Sandbox Code Playgroud)

例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();
});
Run Code Online (Sandbox Code Playgroud)

例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();
});
Run Code Online (Sandbox Code Playgroud)

例4:

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