哪个“href"我应该将值用于 JavaScript 链接,“#"还是“javascript:void(0)"?

以下是构建链接的两种方法,该链接的唯一目的是运行 JavaScript 代码.在功能、页面加载速度、验证目的等方面哪个更好?

The following are two methods of building a link that has the sole purpose of running JavaScript code. Which is better, in terms of functionality, page load speed, validation purposes, etc.?

function myJsFunc() {
    alert("myJsFunc");
}

<a href="#" onclick="myJsFunc();">Run JavaScript Code</a>

function myJsFunc() {
    alert("myJsFunc");
}

 <a href="javascript:void(0)" onclick="myJsFunc();">Run JavaScript Code</a>

推荐答案

我使用 javascript:void(0).

三个原因.鼓励开发人员团队使用 # 不可避免地会导致一些人使用这样调用的函数的返回值:

Three reasons. Encouraging the use of # amongst a team of developers inevitably leads to some using the return value of the function called like this:

function doSomething() {
    //Some code
    return false;
}

但后来他们忘记在 onclick 中使用 return doSomething() 而只使用 doSomething().

But then they forget to use return doSomething() in the onclick and just use doSomething().

避免 # 的第二个原因是,如果被调用的函数抛出错误,最终的 return false; 将不会执行.因此,开发人员还必须记住在被调用函数中适当地处理任何错误.

A second reason for avoiding # is that the final return false; will not execute if the called function throws an error. Hence the developers have to also remember to handle any error appropriately in the called function.

第三个原因是在某些情况下 onclick 事件属性是动态分配的.我更喜欢能够调用函数或动态分配它,而不必专门为一种或另一种连接方法编写函数.因此我在 HTML 标记中的 onclick (或任何东西)看起来像这样:

A third reason is that there are cases where the onclick event property is assigned dynamically. I prefer to be able to call a function or assign it dynamically without having to code the function specifically for one method of attachment or another. Hence my onclick (or on anything) in HTML markup look like this:

onclick="someFunc.call(this)"

onclick="someFunc.apply(this, arguments)"

使用 javascript:void(0) 可以避免上述所有问题,而且我还没有发现任何不利的例子.

Using javascript:void(0) avoids all of the above headaches, and I haven't found any examples of a downside.

因此,如果您是一个单独的开发人员,那么您显然可以做出自己的选择,但如果您作为一个团队工作,您必须声明:

So if you're a lone developer then you can clearly make your own choice, but if you work as a team you have to either state:

使用 href="#",确保 onclick 总是包含 return false; 在最后,任何被调用的函数都不会抛出一个错误,如果您将函数动态附加到 onclick 属性,请确保它返回 false 并且不引发错误.

Use href="#", make sure onclick always contains return false; at the end, that any called function does not throw an error and if you attach a function dynamically to the onclick property make sure that as well as not throwing an error it returns false.

使用 href="javascript:void(0)"

第二个显然更容易沟通.

The second is clearly much easier to communicate.

相关文章