目录

Javascript - Void Keyword

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

语法 (Syntax)

void的语法可以是以下两种语法之一 -

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

例子1 (Example 1)

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

这里表达式alert ('Warning!!!')被评估,但它没有加载回当前文档 -

<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>

输出 (Output)

新页面打开

例子2 (Example 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>

输出 (Output)

新页面打开

例子3 (Example 3)

void另一个用途是故意生成undefined值,如下所示。

<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>

输出 (Output)

新页面打开
↑回到顶部↑
WIKI教程 @2018