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.com/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.