Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

javascript - event.preventDefault()与return false(event.preventDefault() vs. return false)

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?

(有什么更好的方法?)

  ask by RaYell translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

(从jQuery事件处理程序中 return false e.preventDefault与在传递的jQuery.Event对象上调用e.preventDefaulte.stopPropagation相同)

e.preventDefault() will prevent the default event from occuring, e.stopPropagation() will prevent the event from bubbling up and return false will do both.

(e.preventDefault()将阻止发生默认事件, e.stopPropagation()将阻止事件冒泡并return false将同时执行。)

Note that this behaviour differs from normal (non-jQuery) event handlers, in which, notably, return false does not stop the event from bubbling up.

(请注意,此行为与正常 (非jQuery的)事件处理程序不同,其中,值得注意的是, return false 冒泡停止该事件。)

Source: John Resig

(资料来源: John Resig)

Any benefit to using event.preventDefault() over "return false" to cancel out an href click?

(使用event.preventDefault()而不是“return false”取消href点击有什么好处?)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...