event.preventDefault()与return false

╄→尐↘猪︶ㄣ 提交于 2020-10-12 23:52:03

问题:

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!