从点击处理程序返回false在Firefox中不起作用 [英] Returning false from click handler doesn't work in Firefox
问题描述
在下面的示例中,在Firefox 3.6或Chrome中, return false
似乎不会阻止链接被点击后的默认操作(因为页面滚动到顶部) 10但在Internet Explorer中可用。
In the example below, return false
does not seem to prevent the default action after the link is clicked (because the page scrolls to the top) in Firefox 3.6 or Chrome 10 but works in Internet Explorer.
使用 event.preventDefault()
做我需要的,但我想知道为什么 return false
与其他人无法使用。
Using event.preventDefault()
does what I need, but I'm wondering why return false
does not work with the others.
附注: 。
<script>
addEventListener("DOMContentLoaded", function(){
document.getElementById("link").addEventListener("click", function(){
alert("Clicked!");
return false;
}, false);
alert("Click handler bound!");
}, false);
</script>
<div style="margin-top: 1200px;">
<a id="link" href="#">Click me!</a>
</div>
推荐答案
return false
为跨浏览器工作,但仅用于分配DOM0方式的事件处理常式,例如
return false
works cross browser, but only for event handlers assigned the "DOM0" way, such as
document.getElementById("link").onclick = function() {
alert("Clicked!");
return false;
};
对于通过 addEventListener()分配DOM Level 2方法的事件处理程序
,您必须使用
preventDefault()
:
document.getElementById("link").addEventListener("click", function(evt) {
alert("Clicked!");
evt.preventDefault();
}, false);
通过 attachEvent()附加的事件监听器
在IE中, return false
或 window.event.returnValue = false
将执行:
For event listeners attached via attachEvent()
in IE, either return false
or window.event.returnValue = false
will do:
document.getElementById("link").attachEvent("onclick", function() {
alert("Clicked!");
return false;
});
这篇关于从点击处理程序返回false在Firefox中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!