原型 - $() 方法



最常用的便捷功能 $() 可提供獲取 DOM 元素控制權的簡便方法。

語法

$(id | element)

OR

$((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.htm
廣告
© . All rights reserved.