为什么“return false”不起作用?
重要性:3
为什么在下面的代码中 return false 根本不起作用?
<script>
function handler() {
alert( "..." );
return false;
}
</script>
<a href="https://w3.org" onclick="handler()">the browser will go to w3.org</a>
浏览器在点击时会遵循 URL,但我们不希望它这样做。
如何修复?
当浏览器读取 on* 属性(如 onclick)时,它会从其内容中创建处理程序。
对于 onclick="handler()",该函数将是
function(event) {
handler() // the content of onclick
}
现在我们可以看到,handler() 返回的值没有被使用,也不会影响结果。
修复很简单
<script>
function handler() {
alert("...");
return false;
}
</script>
<a href="https://w3.org" onclick="return handler()">w3.org</a>
我们也可以使用 event.preventDefault(),如下所示
<script>
function handler(event) {
alert("...");
event.preventDefault();
}
</script>
<a href="https://w3.org" onclick="handler(event)">w3.org</a>