问题:
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: 我将在示例中使用jQuery,但这也适用于plain-JS:
1. event.preventDefault()
1. event.preventDefault()
$('a').click(function (e) {
// custom handling here
e.preventDefault();
});
2. return false
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;
对我来说, 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? 也许,为什么我应该避免这样做并使用preventDefault
? What's the better way? 有什么更好的方法?
解决方案:
参考一: https://stackoom.com/question/5h30/event-preventDefault-与return-false参考二: https://oldbug.net/q/5h30/event-preventDefault-vs-return-false
来源:oschina
链接:https://my.oschina.net/u/4438370/blog/4458374