我在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的一些规范中?
当前回答
当使用表单时,我们可以使用'return false'来阻止提交。
function checkForm() {
// return true to submit, return false to prevent submitting
}
<form onsubmit="return checkForm()">
...
</form>
其他回答
浏览器黑客: http://jszen.blogspot.com/2007/03/return-false-to-prevent-jumping.html
返回false可以防止页面被导航,也可以防止不必要地将窗口滚动到顶部或底部。
onclick="return false"
我相信它会导致标准事件不发生。
在你的例子中,浏览器不会尝试转到#。
下面是一个更健壮的例程,可以取消所有浏览器中的默认行为和事件冒泡:
// 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);
}
从JavaScript事件中返回false通常会取消“默认”行为——在链接的情况下,它告诉浏览器不要跟踪该链接。