Prototype - $() 方法

最常用和最方便的函数 $() 提供了一种获取 DOM 元素句柄的简单方法。

语法

$(id | element)

或

$((id | element)...)

返回值

  • 找到 HTMLElement。
  • 如果找到多个元素,则返回 HTML 元素数组。

这是编写 Javascript 语句以获取 DOM 节点的旧方法。

node = document.getElementById("elementID");

使用 $(),我们可以将其缩短如下 −

node = $("elementID");

示例

<html>
   <head>
      <title>Prototype examples</title>
      <script type = "text/javascript" src = "/javascript/prototype.js"></script>
      
      <script>
         function test() {
            node = $("firstDiv");
            alert(node.innerHTML);
         }
      </script>
   </head>

   <body>
      <div id = "firstDiv">
         <p>This is first paragraph</p> 
      </div>
      
      <div id = "secondDiv">
         <p>This is another paragraph</p>
      </div>    
      
      <input type = "button" value = "Test $()" onclick = "test();"/>
   </body>
</html>

输出

使用 $() 获取多个值

$() 函数也比 document.getElementById() 更强大,因为检索多个元素的能力内置于该函数中。

此函数的另一个优点是您可以传递 id 字符串或元素对象本身,这使得此函数在创建其他也可以采用任一形式参数的函数时非常有用。

示例

在此示例中,我们看到 $() 函数现在返回元素的数组,然后可以使用简单的 for 循环访问该数组。

<html>
   <head>
      <title>Prototype examples</title>
      <script type = "text/javascript" src = "/javascript/prototype.js"></script>
      
      <script>
         function test() {
            allNodes = $("firstDiv", "secondDiv");
            
            for(i = 0; i < allNodes.length; i++) {
               alert(allNodes[i].innerHTML);
            } 
         }
      </script>
   </head>

   <body>
      <div id = "firstDiv">
         <p>This is first paragraph</p> 
      </div>
      
      <div id = "secondDiv">
         <p>This is another paragraph</p>
      </div>
      
      <input type = "button" value = "Test $()" onclick = "test();"/>
   </body>
</html>

输出

prototype_utility_methods.html