其中“href"我应该将值用于 JavaScript 链接,“#";还是“javascript:void(0)"? [英] Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

查看:36
本文介绍了其中“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.

这篇关于其中“href"我应该将值用于 JavaScript 链接,“#";还是“javascript:void(0)"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆