JavaScript:Void(0)是什么意思?

JavaScript’s void operator evaluates an expression and returns undefined.

JavaScript的void运算符计算一个表达式并返回未定义。

You can use the console to verify the same:

您可以使用控制台进行验证:

Note: void, irrespective of any value passed along, *always returns undefined as shown above*. But, void with the operand 0 is preferred.

注意void无论传递的是什么值,*总是返回undefined,如上所示*。 但是, 首选操作数为0的 void

There are two ways of using operand 0: void(0) or void 0. Either of them is fine.

有两种使用操作数0的方法:void(0)或void0。这两种方法都可以。

何时使用Javascript void(0) (When to use Javascript void(0))

Use javascript:void(0) if, when a link is clicked, you don’t want the browser to load a new page or refresh the same page (depending on the URL specified).

如果在单击链接时不希望浏览器加载新页面或刷新同一页面(取决于指定的URL),请使用javascript:void(0)。

Instead it will just perform the JavaScript attached to that link.

相反,它将只执行附加到该链接JavaScript。

带有JavaScript void(0)的示例1: (Example 1 with Javascript void(0):)

<html>
<body>
<a href="javascript:void(0);alert('Hello ! I am here')">Click Me</a>
</body>
</html>
输出: (Output:)

When someone clicks on the ClickMe link, an alert pops up as below:

当有人单击ClickMe链接时,将弹出如下警告:

带有JavaScript void(0)的示例2: (Example 2 with Javascript void(0):)

<html>
<body>
<a href="javascript:void(0)" ondblclick="alert('Hi,i didnt refresh the page')" )>Click Me</a>
</body>
</html>
输出: (Output:)

When you double click the link, an alert will popup without any page refresh.

双击链接时,将弹出警报,而不会刷新任何页面。

带有JavaScript void(0)的示例3: (Example 3 with Javascript void(0):)

<html>
<body>
<a href="javascript:void(0);https://www.google.co.in/" 
ondblclick="alert('Hello !! You will see me and not get redirected to google.com ')">Click Me</a>
</body>
</html>
输出: (Output:)

When you double click the link, an alert will popup. Closing it will also not redirect to google.com.

当您双击链接时,将弹出警报。 关闭它也不会重定向到google.com。

没有Javascript void(0)的示例: (Example without Javascript void(0):)

<html>
<body>
<a href="https://www.google.co.in/" ondblclick="alert('Hello !! You will see me and then get redirected to google.com even if not needed')">Click Me</a>
</body>
</html>
输出: (Output:)

When you double click the link, an alert will popup, but closing it will redirect to google.com.

当您双击该链接时,将弹出一个警报,但关闭该警报将重定向到google.com。

结论 (Conclusion)

The void operator is useful when you need to prevent any unwanted page refresh or redirection. Rather, it performs some JavaScript operation.

当您需要防止任何不需要的页面刷新或重定向时, void运算符很有用。 而是执行一些JavaScript操作。

更多信息: (More Information:)
  1. Mozilla Docs

    Mozilla文件

翻译自: https://www.freecodecamp.org/news/what-does-javascript-void-operator-do/

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值