我在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的一些规范中?
当前回答
我的html页面上有这个链接:
<a href = ""
onclick = "setBodyHtml ('new content'); return false; "
> click here </a>
函数setBodyHtml()被定义为:
function setBodyHtml (s)
{ document.body.innerHTML = s;
}
当我点击链接,链接消失,文本显示在浏览器中 更改“新内容”。
但是如果我从我的链接中删除“false”,点击链接(似乎)什么都没有。为什么呢?
这是因为如果我不返回false,点击链接并显示其目标页面的默认行为就会发生,不会取消。但是,这里超链接的href是“”,所以它链接回相同的当前页面。因此,页面实际上只是被刷新,似乎什么也没有发生。
在后台,函数setBodyHtml()仍然被执行。它将参数赋值给body.innerHTML。但是由于页面会立即刷新/重新加载,修改后的主体内容可能不会在几毫秒内保持可见,所以我不会看到它。
这个例子说明了为什么有时使用“return false”是有用的。
我确实想给这个链接赋值somehref,这样它就会显示为一个链接,作为带下划线的文本。但我不希望点击链接只是有效地重新加载页面。我希望默认的navigation=行为被取消,并且调用我的函数所引起的任何副作用都保持有效。因此,我必须“返回false”。
上面的例子是您在开发过程中可以快速尝试的。对于生产,您更可能在JavaScript中分配一个点击处理程序,并调用preventDefault()。但是对于一个快速的尝试,上面的“return false”就可以了。
其他回答
返回false将阻止导航。否则,位置将成为someFunc的返回值
返回false表示不采取默认操作,在<a href>的情况下,默认操作是遵循链接。当你对onclick返回false时,href将被忽略。
返回false可以防止页面被导航,也可以防止不必要地将窗口滚动到顶部或底部。
onclick="return 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
下面是一个更健壮的例程,可以取消所有浏览器中的默认行为和事件冒泡:
// 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);
}