如何透過 ID、類、標記和屬性在 jQuery 中獲取物件?


以下是如何透過 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>

更新於:2019 年 12 月 9 日

845 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.