我在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的一些规范中?
当前回答
在onclick事件中使用return false将阻止浏览器处理执行堆栈的其余部分,包括遵循href属性中的链接。
换句话说,添加return false会使href停止工作。在你的例子中,这正是你想要的。
在按钮中,这是不必要的,因为onclick是它将执行的所有操作——没有href来处理和前往。
其他回答
我相信它会导致标准事件不发生。
在你的例子中,浏览器不会尝试转到#。
下面是一个更健壮的例程,可以取消所有浏览器中的默认行为和事件冒泡:
// 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);
}
返回false将在javascript运行后停止跟踪超链接。这对于优雅地降级的不引人注目的javascript非常有用——例如,你可以有一个缩略图,使用javascript打开一个全尺寸图像的弹出窗口。当javascript被关闭或图像被中间点击(在一个新的选项卡中打开)时,它会忽略onClick事件,只是正常地以完整尺寸的图像打开图像。
如果没有指定return false,图像将正常启动弹出窗口并打开图像。有些人不使用return false,而是使用javascript作为href属性,但这意味着当javascript被禁用时,链接将什么都不做。
从JavaScript事件中返回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