如何在 jQuery 中通过 ID、类、标签和属性获取对象?

jqueryweb developmentfront end technology

以下是如何通过 ID 选择器 (#id)、类选择器 (.class)、标签和属性 (.attr()) 获取对象的方法。

通过类选择器获取对象

示例

元素类选择器选择所有与给定类匹配的元素。

<html>
   <head>
      <title>jQuery Selector</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   
      <script>
         $(document).ready(function() {    
            $(".big").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>

   </body>
</html>

通过 ID 选择器获取对象

示例

元素 ID 选择器选择具有给定 id 属性的单个元素:

<html>
   <head>
      <title>jQuery Selector</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
         $(function(){
           $("#submit").click(function(){      
             alert($('input:radio:checked').val());
          });
         });
      </script>
   </head>
   <body>
      <form id="myForm">
         Select a number:<br>
         <input type="radio" name="q1" value="1">1
         <input type="radio" name="q1" value="2">2
         <input type="radio" name="q1" value="3">3<br>
         <button id="submit">Result</button>
      </form>
   </body>
</html>

通过标签获取对象

示例

为此,请传递特定标签的名称,即下面的 <a> 标签:

<html>
   <head>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
         $(document).ready(function(){
          $("a").click(function(){
            $("a.active").removeClass("active");
            $(this).addClass("active");
           });
         });
      </script>
      <style>
         .active {
            font-size: 22px;  
         }
      </style>
   </head>
   <body>
      <a href="#" class="">One</a>
      <a href="#" class="">Two</a>
      <p>Click any of the link above and you can see the changes.</p>
   </body>
</html>

通过属性获取对象

示例

使用 .attr() 函数,您可以获取任意标签的任意属性。以下示例展示了如何获取属性值:

<html>

   <head>
      <title>jQuery Example</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

      <script>
      $(document).ready(function(){
         $("button").click(function(){
            $("img").attr("height", "200");
         });
      });
      </script>
   </head>
   
   <body>
      <img src="/green/images/logo.png" alt="logo" width="450" height="160"><br>
      <button>Change the height</button>
   </body>
   
</html>

相关文章