我什么时候应该在 jquery 函数中使用 return false ? [英] When should I use return false in jquery function?
问题描述
我发现了很多这样的函数:
I found lots of functions like this one:
$(function() {
$("body a").click(function() {
alert(this.innerHTML);
return false;
});
});
jquery中this
和$(this)
的区别是什么?
What's the difference between this
and $(this)
in jquery?
他们都有一行 return false;
- 我不知道什么时候应该在 jquery 函数中使用 return false
并且不知道它有什么用?
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?
推荐答案
根据 jQuery Events: Stop (Mis)Using Return False(存档链接),调用时返回false
执行三个任务:
According to jQuery Events: Stop (Mis)Using Return False (archived link), returning false
performs three tasks when called:
- event.preventDefault();
- event.stopPropagation();
- 停止回调执行并在调用时立即返回.
取消默认行为所需的唯一操作是preventDefault()
.发出 return false;
可以创建脆弱的代码.通常你只想要这个:
The only action needed to cancel the default behaviour is preventDefault()
. Issuing return false;
can create brittle code. Usually you'd want just this:
$("a").on( 'click', function (e) {
// e == our event data
e.preventDefault();
});
其次this"是javascript中的DOM元素,$(this)"是jQuery元素引用 DOM 元素.在 jQuery's this: demystified 阅读有关该主题的更多信息.
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.
这篇关于我什么时候应该在 jquery 函数中使用 return false ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!