JavaScript - Void关键字

void 是JavaScript中的一个重要关键字,可以用作在单个操作数之前出现的一元运算符,该操作数可以是任何类型。此运算符指定要计算的表达式而不返回值。

语法

void 的语法可以是以下两个 :

<head>
   <script type = "text/javascript">
      <!--
         void func()
         javascript:void func()
         or:
         void(func())
         javascript:void(func())
      //-->
   </script>
</head>


示例1

此运算符的最常见用法是在客户端 javascript: URL,它允许您在没有浏览器显示已计算表达式的值的情况下评估表达式的副作用。

此处表达式 alert('警告!!!')被评估,但它没有加载回当前文档 :

在线演示

<html>
   <head>      
      <script type = "text/javascript">
         <!--
         //-->
      </script>   
   </head>
   
   <body>   
      <p>Click the following, This won't react at all...</p>
      <a href = "javascript:void(alert('Warning!!!'))">Click me!</a>     
   </body>
</html>


示例 2

看一下下面的例子。 以下链接不起作用,因为表达式"0"在JavaScript中没有效果。 这里表达式"0"被计算,但它没有被加载回当前文档。

在线演示

<html>
   <head>   
      <script type = "text/javascript">
         <!--
         //-->
      </script>      
   </head>
   
   <body>   
      <p>Click the following, This won't react at all...</p>
      <a href = "javascript:void(0)">Click me!</a>      
   </body>
</html>

示例 3

void的另一个用途是故意生成未定义的值,如下所示。

在线演示

<html>
   <head>      
      <script type = "text/javascript">
         <!--
            function getValue() {
               var a,b,c;
               
               a = void ( b = 5, c = 7 );
               document.write('a = ' + a + ' b = ' + b +' c = ' + c );
            }
         //-->
      </script>      
   </head>
   
   <body>
      <p>Click the following to see the result:</p>
      <form>
         <input type = "button" value = "Click Me" onclick = "getValue();" />
      </form>     
   </body>
</html>