我在HTML页面中见过很多这样的链接:
<a href='#' onclick='someFunc(3.1415926); return false;'>Click here !</a>
这里return false的效果是什么?
而且,我通常不会在按钮中看到这种情况。
这在任何地方都指定了吗?在w3.org的一些规范中?
我在HTML页面中见过很多这样的链接:
<a href='#' onclick='someFunc(3.1415926); return false;'>Click here !</a>
这里return false的效果是什么?
而且,我通常不会在按钮中看到这种情况。
这在任何地方都指定了吗?在w3.org的一些规范中?
当前回答
默认情况下,当您单击按钮时,无论您输入了什么值,表单都将被发送到服务器。
然而,这种行为在大多数情况下不太合适,因为我们可能想在发送到服务器之前做一些检查。
因此,当侦听器收到“false”时,提交将被取消。基本上,它的目的是在前端做一些检查。
其他回答
浏览器黑客: http://jszen.blogspot.com/2007/03/return-false-to-prevent-jumping.html
我很惊讶没有人提到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
在onclick事件中使用return false将阻止浏览器处理执行堆栈的其余部分,包括遵循href属性中的链接。
换句话说,添加return false会使href停止工作。在你的例子中,这正是你想要的。
在按钮中,这是不必要的,因为onclick是它将执行的所有操作——没有href来处理和前往。
你可以从下面的例子中看出区别:
<a href="http://www.google.co.uk/" onclick="return (confirm('Follow this link?'))">Google</a>
单击“ok”返回true,然后是链接。点击“取消”返回false,并且不遵循链接。如果javascript被禁用,链接是正常的。
返回false表示不采取默认操作,在<a href>的情况下,默认操作是遵循链接。当你对onclick返回false时,href将被忽略。