javascript:void(0)或onclick= " return false " for -哪个更好?

时间:2022-08-05 20:19:25

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?

每种方法的优缺点是什么?

2 个解决方案

#1


10  

Both are poor choices. Presentation shouldn't mix with content. That means no javascript: URIs, and definitely no onclick attributes.

都是可怜的选择。演示不应该与内容混淆。这意味着没有javascript: uri,而且绝对没有onclick属性。

The way to do it:

方法:

<a id="myLink">Something</a>
<script>
    function myFunction(...) { ... }
    document.getElementById('myLink').addEventListener('click', myFunction, false);
</script>

#2


2  

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.

既不。如果你的链接哪里都没有,不要使用元素。使用或其他适当的东西,并添加CSS来按照您的意愿进行样式化。

#1


10  

Both are poor choices. Presentation shouldn't mix with content. That means no javascript: URIs, and definitely no onclick attributes.

都是可怜的选择。演示不应该与内容混淆。这意味着没有javascript: uri,而且绝对没有onclick属性。

The way to do it:

方法:

<a id="myLink">Something</a>
<script>
    function myFunction(...) { ... }
    document.getElementById('myLink').addEventListener('click', myFunction, false);
</script>

#2


2  

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.

既不。如果你的链接哪里都没有,不要使用元素。使用或其他适当的东西,并添加CSS来按照您的意愿进行样式化。