为什么要使用 void(0)? [英] Why use void(0)?

查看:50
本文介绍了为什么要使用 void(0)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们暂时假设您必须创建一个没有有意义的 href 的 JavaScript 链接.(我知道这种做法是有问题的.)在这种情况下,为什么这么多人使用...

Let's assume for a moment that you must create a JavaScript link that doesn't have a meaningful href. (I know that this practice is questionable.) In this case, why do so many people use...

<a href="javascript:void(0);"> My link </a> 

知道 void(0) 的计算结果是 undefined,我可以简单地使用以下逻辑吗?

Knowing that void(0) evaluates to undefined, can I simply use the following logic?

<a href="javascript:undefined;"> My link </a>

推荐答案

为什么人们使用 void(x) 而不是 undefined?

Why people use void(x) instead of undefined?

两者都可以,但是 undefined 是一个保留变量,它的值可以改变:

Well both would work but undefined is a reserved variable and its value can be changed:

undefined = true;

这将给出 true 而不是 undefined.

This will give true instead of undefined.

其中 void() 是一个关键字它总是返回 undefined. 无论您在关键字中放置什么:

Where as void() is a keyword which always returns undefined. Whatever you place inside the keyword:

void('return false plox');//将返回false

有关此主题的更多信息:`void 0` 是什么意思?

More info on this topic here: What does `void 0` mean?

注意 不一样,因为它仍然充当链接并会重定向您,而前面的方法将取消事件(类似于 event.preventDefault).

Note that <a href="#"> is not the same as it still acts as a link and will redirect you, where as the previous methods will cancel the event(similar to event.preventDefault).

更新

自 ECMAScript 5 起,全局 undefined 变量不再可直接编辑(参见 Mozilla 文档示例).正如某些人所指出的那样,它现在只是隐藏了全局变量.

Since ECMAScript 5, the global undefined variable is no longer directly editable (See for example Mozilla docs). It now simply shadows the global variable as some have noted.

这篇关于为什么要使用 void(0)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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