我在HTML页面中见过很多这样的链接:

<a href='#' onclick='someFunc(3.1415926); return false;'>Click here !</a>

这里return false的效果是什么?

而且,我通常不会在按钮中看到这种情况。

这在任何地方都指定了吗?在w3.org的一些规范中?


当前回答

我很惊讶没有人提到onmousedown而不是onclick。的

onclick = '返回假'

没有捕捉浏览器的默认行为,导致(有时不需要的)文本选择发生鼠标下拉,但是

onmousedown = '返回假'

所做的事。

In other words, when I click on a button, its text sometimes becomes accidentally selected changing the look of the button, that may be unwanted. That is the default behaviour that we are trying to prevent here. However, the mousedown event is registered before click, so if you only prevent that behaviour inside your click handler, it will not affect the unwanted selection arising from the mousedown event. So the text still gets selected. However, preventing default for the mousedown event will do the job.

参见event.preventDefault() vs. return false

其他回答

我很惊讶没有人提到onmousedown而不是onclick。的

onclick = '返回假'

没有捕捉浏览器的默认行为,导致(有时不需要的)文本选择发生鼠标下拉,但是

onmousedown = '返回假'

所做的事。

In other words, when I click on a button, its text sometimes becomes accidentally selected changing the look of the button, that may be unwanted. That is the default behaviour that we are trying to prevent here. However, the mousedown event is registered before click, so if you only prevent that behaviour inside your click handler, it will not affect the unwanted selection arising from the mousedown event. So the text still gets selected. However, preventing default for the mousedown event will do the job.

参见event.preventDefault() vs. return false

什么“返回错误”是真的做?

当你调用它时,Return false实际上做了三件非常独立的事情:

event.preventDefault (); event.stopPropagation (); 停止回调执行并在调用时立即返回。

更多信息请参见jquery-events-stop- misuse -return-false。

例如:

当单击此链接时,返回false将取消浏览器的默认行为。

<a href='#' onclick='someFunc(3.1415926); return false;'>Click here !</a>

返回false将在javascript运行后停止跟踪超链接。这对于优雅地降级的不引人注目的javascript非常有用——例如,你可以有一个缩略图,使用javascript打开一个全尺寸图像的弹出窗口。当javascript被关闭或图像被中间点击(在一个新的选项卡中打开)时,它会忽略onClick事件,只是正常地以完整尺寸的图像打开图像。

如果没有指定return false,图像将正常启动弹出窗口并打开图像。有些人不使用return false,而是使用javascript作为href属性,但这意味着当javascript被禁用时,链接将什么都不做。

事件处理程序的返回值决定是否也应该发生默认的浏览器行为。在单击链接的情况下,这将跟随链接,但在表单提交处理程序中最明显的区别是,如果用户在输入信息时犯了错误,您可以取消表单提交。

我不相信有一个W3C规范。像这样的所有古老的JavaScript接口都被冠以“DOM 0”的绰号,而且大多数都没有具体说明。您可以有幸阅读旧的Netscape 2文档。

实现这种效果的现代方法是调用event.preventDefault(),这在DOM 2 Events规范中指定。

默认情况下,当您单击按钮时,无论您输入了什么值,表单都将被发送到服务器。

然而,这种行为在大多数情况下不太合适,因为我们可能想在发送到服务器之前做一些检查。

因此,当侦听器收到“false”时,提交将被取消。基本上,它的目的是在前端做一些检查。