2010-06-15 46 views
8

据说,当我们处理“点击事件”,返回false或者调用event.preventDefault()有差别,其中在JavaScript事件处理中,为什么“返回false”或“event.preventDefault()”和“停止事件流”会有所作为?

不同的是,的preventDefault 只会阻止默认事件 行动发生,即页面重定向 上的链接点击,表单提交, 等,并返回false也会停止 事件流。

这是否意味着,如果点击事件被注册多次采取若干行动,使用

$('#clickme').click(function() { … }) 

返回false将停止运行其他的处​​理程序?

我现在在Mac上,所以只能使用Firefox和Chrome,但不能使用具有不同事件模型的IE,并且通过添加3个处理程序在FF和Chrome上测试它,并且所有3个处理程序都不会停止运行。 。所以真正的区别是什么,或者,是否存在“停止事件流”不可取的情况?

这是关系到

Using jQuery's animate(), if the clicked on element is "<a href="#" ...> </a>", the function should still return false?

What's the difference between e.preventDefault(); and return false?

+0

请参见:[事件流程](http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-flow) – CMS 2010-06-15 02:25:11

回答

13

希望这个代码可以解释给你听......

HTML

<div> 
<a href="index.html" class="a1">click me</a> 
<a href="index.html" class="a2">click me</a> 
</div>​ 

jQuery的

$('div').click(function(){ 
    alert('I am from <div>'); 
}); 

$('a.a1').click(function(){ 
    alert('I am from <a>'); 
    return false; // this will produce one alert 
}); 

$('a.a2').click(function(e){ 
    alert('I am from <a>'); 
    e.preventDefault(); // this will produce two alerts 
});​ 

demo

$('div').click(function(){ 
    alert('I am from <div>'); 
}); 

$('a').click(function(){ 
    alert('I am from <a>'); 
}); 

$('a.a1').click(function(){ 
    alert('I am from <a class="a1">'); 
    return false; 
}); 

$('a.a2').click(function(e){ 
    alert('I am from <a class="a2">'); 
    e.preventDefault(); 
});​ 

demo 2

9

return falsee.preventDefault()不会阻止其他处理程序运行。

相反,它们会阻止浏览器的默认响应,例如导航到链接。

在jQuery中,您可以编写e.stopImmediatePropagation()以防止其他处理程序运行。

0

这并不完全回答你的问题,但有一天,我使用YUI的e.preventDefault()<a>元素压制该href行动,我只是想在JavaScript的onclick事件有控制(除非没有JS检测)。在这种情况下,停止整个事件链不会影响我。前

不过几天,我有嵌套在<label>元素中的<input type="checkbox">,我不得不使用条件在事件处理程序,以确定是否被点击的目标是一个标签,既不e.preventDefault()也不e.stopEvent()停在我的“点击'(legitimately)事件触发两次(IE6除外)。

本来不错的是可以压缩整个相关事件链,因为我已经尝试过传播和return false ;,但是我总是会因为我的标签元素而得到第二个事件。


编辑:我不介意jquery如何处理我的双重事件情况,如果有人热衷于评论这件事。

1

有时候事件监听器想要取消事件的副作用感兴趣。想象一下你希望只允许数字的文本框。由于文本框可以接受任何事情,因此有必要告诉浏览器忽略键入的非数字。这是通过监听关键事件并在错误键被键入时返回false来实现的。

2

return falsepreventDefault()是否存在以防止浏览器与某个事件相关联的默认操作(例如,点击时链接下面的链接)。有三种不同的方法可以实现这一点:

1.使用addEventListener()(非IE浏览器)添加的事件处理程序。在这种情况下,请使用Event对象的preventDefault()方法。其他的事件处理程序仍然会被调用。使用attachEvent()(IE)

function handleEvent(evt) { 
    evt.preventDefault(); 
} 

2.一种事件处理程序添加。在这种情况下,请将window.eventreturnValue属性设置为true。该事件的其他处理程序仍将被调用,并且也可能会更改此属性。

function handleEvent() { 
    window.event.returnValue = false; 
} 

3.一种事件处理程序使用属性或事件处理程序属性加入。

<input type="button" value="Do stuff!" onclick="return handleEvent(event)"> 

button.onclick = handleEvent; 

在这种情况下,return false将做的工作。通过addEventListener()attachEvent()添加的任何其他事件处理程序仍将被调用。

function handleEvent() { 
    return false; 
} 
相关问题