我在HTML页面中多次看到这样的链接:
<a href='#' onclick='someFunc(3.1415926); return false;'>Click here !</a>
里面的return false
有什么作用呢?
而且,我通常不会在按钮中看到这一点。
这是在任何地方指定的吗?在w3.org中的某个规范中?
发布于 2008-09-24 18:36:18
事件处理程序的返回值确定是否也应该发生默认浏览器行为。在单击链接的情况下,这将跟随链接,但在表单提交处理程序中差异最明显,在表单提交处理程序中,如果用户输入了错误的信息,则可以取消表单提交。
我不相信有这样的W3C规范。所有像这样的古老的JavaScript接口都被赋予了"DOM 0“的昵称,并且大多数都是未指定的。你可能会有一些运气阅读旧的Netscape 2文档。
实现此效果的现代方法是调用event.preventDefault()
,这是在the DOM 2 Events specification中指定的。
发布于 2008-09-25 09:52:17
您可以从以下示例中看到不同之处:
<a href="http://www.google.co.uk/" onclick="return (confirm('Follow this link?'))">Google</a>
单击“is”返回true,并跟随链接。单击"Cancel“将返回false,并且不会跟随该链接。如果javascript被禁用,该链接将被正常跟踪。
发布于 2008-09-24 19:59:40
这里有一个更健壮的例程来取消所有浏览器中的默认行为和事件冒泡:
// Prevents event bubble up or any usage after this is called.
eventCancel = function (e)
{
if (!e)
if (window.event) e = window.event;
else return;
if (e.cancelBubble != null) e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
if (e.preventDefault) e.preventDefault();
if (window.event) e.returnValue = false;
if (e.cancel != null) e.cancel = true;
}
下面是一个如何在事件处理程序中使用它的示例:
// Handles the click event for each tab
Tabstrip.tabstripLinkElement_click = function (evt, context)
{
// Find the tabStrip element (we know it's the parent element of this link)
var tabstripElement = this.parentNode;
Tabstrip.showTabByLink(tabstripElement, this);
return eventCancel(evt);
}
https://stackoverflow.com/questions/128923
复制相似问题