event.preventDefault()vs. return false [英] event.preventDefault() vs. return false
问题描述
当我想防止其他事件处理程序在某个事件触发后执行时,我可以使用两种技术之一。我将在示例中使用jQuery,但这也适用于plain-JS:
1。 event.preventDefault()
$('a')点击(function(e){
// custom handling here
e.preventDefault();
});
2。 return false
$('a')click(function ){
// custom handling here
return false;
});
这两种阻止事件传播的方法有什么区别?
对于我来说, return false;
比执行方法更简单,更短,更不容易出错。使用该方法,您必须记住正确的套管,括号等。
此外,我必须在回调中定义第一个参数才能调用该方法。也许,有一些原因,为什么我应该避免这样做,并使用 preventDefault
而不是?什么是更好的方法?
返回false
一个jQuery事件处理程序与在 e.preventDefault
和 e.stopPropagation
传递了 jQuery.Event对象。
e.preventDefault()
将阻止默认事件发生, e.stopPropagation()
将防止事件冒泡,并且 return false
将同时执行。请注意,此行为与正常(非jQuery)事件处理程序不同,其中特别是返回false
不资料来源: John Resig
使用event.preventDefault()超过return false取消href点击的任何好处?
When I want to prevent other event handlers from executing after a certain event is fired, I can use one of two techniques. I'll use jQuery in the examples, but this applies to plain-JS as well:
1. event.preventDefault()
$('a').click(function (e) {
// custom handling here
e.preventDefault();
});
2. return false
$('a').click(function () {
// custom handling here
return false;
});
Is there any significant difference between those two methods of stopping event propagation?
For me, return false;
is simpler, shorter and probably less error prone than executing a method. With the method, you have to remember about correct casing, parenthesis, etc.
Also, I have to define the first parameter in callback to be able to call the method. Perhaps, there are some reasons why I should avoid doing it like this and use preventDefault
instead? What's the better way?
return false
from within a jQuery event handler is effectively the same as calling both e.preventDefault
and e.stopPropagation
on the passed jQuery.Event object.
e.preventDefault()
will prevent the default event from occuring, e.stopPropagation()
will prevent the event from bubbling up and return false
will do both. Note that this behaviour differs from normal (non-jQuery) event handlers, in which, notably, return false
does not stop the event from bubbling up.
Source: John Resig
Any benefit to using event.preventDefault() over "return false" to cancel out an href click?
这篇关于event.preventDefault()vs. return false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!