<a> 的 javascript:void(0) 或 onclick="return false" - 哪个更好?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3465750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript:void(0) or onclick="return false" for <a> - which is better?
提问by Sir Hally
There is a javascript-based interface - so I need not to support work without javascript.
有一个基于 javascript 的界面 - 所以我不需要支持没有 javascript 的工作。
I have an
我有一个
<a>Something</a>
elements with JS code, which binds on click event - so, I don't want page reload after user's click.
带有 JS 代码的元素,它绑定在点击事件上 - 所以,我不希望在用户点击后重新加载页面。
Which way is better?
哪种方式更好?
1. <a href="javascript:void(0)">Something</a>
2. <a href="#" onclick="return false;">Something</a>
What advantages and disadvantages of each method?
每种方法的优缺点是什么?
采纳答案by Delan Azabani
Both are poor choices. Presentation shouldn't mix with content. That means no javascript:URIs, and definitely no onclickattributes.
两者都是糟糕的选择。演示文稿不应与内容混合。这意味着没有javascript:URI,也绝对没有onclick属性。
The way to do it:
这样做的方法:
<a id="myLink">Something</a>
<script>
function myFunction(...) { ... }
document.getElementById('myLink').addEventListener('click', myFunction, false);
</script>
回答by Tim Down
Neither. If your link doesn't go anywhere, don't use an <a>element. Use a <span>or something else appropriate and add CSS to style it as you wish.
两者都不。如果您的链接无处可去,请不要使用<a>元素。使用 a<span>或其他适当的东西并添加 CSS 以根据需要设置样式。

