Javascript 我什么时候应该在 jquery 函数中使用 return false ?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5927689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When should I use return false in jquery function?
提问by zhuanzhou
I found lots of functions like this one:
我发现了很多这样的功能:
$(function() {
$("body a").click(function() {
alert(this.innerHTML);
return false;
});
});
What's the difference between this
and $(this)
in jquery?
jquerythis
和$(this)
jquery 有什么区别?
They all have a line return false;
- I don't know when I should use return false
in jquery function and don't know what's the use of it?
他们都有一条线return false;
——我不知道什么时候应该return false
在 jquery 函数中使用,也不知道它有什么用?
回答by gruntled
According to jQuery Events: Stop (Mis)Using Return False(archived link), returning false
performs three tasks when called:
根据jQuery Events: Stop (Mis)Using Return False(archived link),返回false
在调用时执行三个任务:
- event.preventDefault();
- event.stopPropagation();
- Stops callback execution and returns immediately when called.
- event.preventDefault();
- event.stopPropagation();
- 停止回调执行并在调用时立即返回。
The only action needed to cancel the default behaviour is preventDefault()
. Issuing return false;
can create brittle code. Usually you'd want just this:
取消默认行为所需的唯一操作是preventDefault()
。发布return false;
可以创建脆弱的代码。通常你只想要这个:
$("a").on( 'click', function (e) {
// e == our event data
e.preventDefault();
});
And secondly "this" is a DOM element in javascript and "$(this)" is a jQuery element that references the DOM element. Read more on the topic at jQuery's this: demystified.
其次,“this”是javascript中的DOM元素,“$(this)”是引用DOM元素的jQuery元素。在jQuery 的 this: demystified上阅读有关该主题的更多信息。
回答by Kon
You're clicking on an anchor, whose default behavior is to navigate somewhere. Returning false may be an attempt to prevent the navigation and keep user on current page/view.
您正在单击一个锚点,其默认行为是导航到某个地方。返回 false 可能是为了阻止导航并使用户保持在当前页面/视图上。
回答by Rob Cowie
In the scope of the click handler, this
is the unwrapped DOM element. $(this)
wraps it and returns a jQuery element. It is common practice to wrap this once and make it available within the scope as that
, or often $this
(prefixing variable names with $ is a convention to indicate a jQuery element).
在单击处理程序的范围内,this
是解包的 DOM 元素。$(this)
包装它并返回一个 jQuery 元素。通常的做法是将它包装一次并使其在范围内可用that
,或者经常$this
(用 $ 前缀变量名是指示 jQuery 元素的约定)。
Your example could therefore be written as
因此,您的示例可以写为
$(function() {
$("body a").click(function() {
var $this = $(this);
alert($this.html());
return false;
});
});