jQuery - 元素 ID 選擇器



描述

元素 ID 選擇器用於選擇具有給定 id 屬性的單個元素。

語法

以下是使用此選擇器的簡單語法:

$('#elementid')

引數

以下是此選擇器使用所有引數的描述:

  • elementid - 這是元素 ID。如果 ID 包含任何特殊字元(如句點或冒號),則必須使用反斜槓轉義這些字元。

返回值

與任何其他 jQuery 選擇器一樣,此選擇器也返回一個包含找到元素的陣列。

示例

  • $('#myid') - 選擇具有給定 ID myid 的單個元素。

  • $('div#yourid') - 選擇具有給定 ID yourid 的單個 div 元素。

以下示例將選擇第二個 div 元素,並將其背景顏色設定為黃色:

<html>
   <head>
      <title>The Selecter Example</title>
      <script type = "text/javascript" 
         src = "https://tutorialspoint.tw/jquery/jquery-3.6.0.js">
      </script>
   
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            /* This would select second division only*/
            $("#div2").css("background-color", "yellow");
         });
      </script>
   </head>
	
   <body>
      <div class = "big" id = "div1">
         <p>This is first division of the DOM.</p>
      </div>

      <div class = "medium" id = "div2">
         <p>This is second division of the DOM.</p>
      </div>

      <div class = "small" id = "div3">
         <p>This is third division of the DOM</p>
      </div>
   </body>
</html>

這將產生以下結果:

jquery-selectors.htm
廣告

© . All rights reserved.