event.preventDefault() 与返回 false [英] event.preventDefault() vs. return false

查看:30
本文介绍了event.preventDefault() 与返回 false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我想阻止其他事件处理程序在某个事件被触发后执行时,我可以使用两种技术之一.我将在示例中使用 jQuery,但这也适用于普通 JS:

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:

$('a').click(function (e) {
    // custom handling here
    e.preventDefault();
});

2.返回错误

$('a').click(function () {
    // custom handling here
    return false;
});

这两种停止事件传播的方法有什么显着区别吗?

Is there any significant difference between those two methods of stopping event propagation?

对我来说,return false; 比执行一个方法更简单、更短并且可能更不容易出错.使用该方法,您必须记住正确的大小写、括号等.

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.

此外,我必须在回调中定义第一个参数才能调用该方法.也许,有一些原因为什么我应该避免这样做并使用 preventDefault 代替?什么是更好的方法?

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 实际上与同时调用 e 相同.preventDefaulte.stopPropagation 在传递的 jQuery.Event 对象.

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() 将阻止默认事件发生,e.stopPropagation() 将阻止事件冒泡并 return false代码> 两者都可以.请注意,此行为与普通(非 jQuery)事件处理程序不同,其中值得注意的是,return false不会阻止事件冒泡

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.

来源:John Resig<​​/a>

Source: John Resig

使用 event.preventDefault() 的任何好处通过return false"取消 href 点击?

这篇关于event.preventDefault() 与返回 false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆