我在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);
}

你可以从下面的例子中看出区别:

<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将被忽略。

返回false可以防止页面被导航,也可以防止不必要地将窗口滚动到顶部或底部。

onclick="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>