如何獲取 $(this) 選擇器的子元素?


要獲取 jQuery 中 $(this) 選擇器的子元素,使用 find() 方法和 each() 方法。我們首先來看看如何新增 jQuery

示例

可以嘗試執行以下程式碼以獲取 $(this) 選擇器的子元素

線上演示

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

         // Set the click handler on your div
         $("body").off("click", "#mydiv").on("click", "#mydiv", function() {
         
           // Find the image using.find() and .each()
           $(this).find("img").each(function() {
         
              var img = this;
         
           });
         });
         
      </script>
      <style>
         #mydiv {
            vertical-align: middle;
            background-color: #Ffff76;
            cursor: pointer;
            padding: 20px;
         }
      </style>
   </head>
   <body>
      <div id="mydiv">
         <img src="/green/images/logo.png" width="300" height="100"/>
      </div>
   </body>
</html>

更新於:2019 年 12 月 18 日

79 次瀏覽

開啟你的 職業 生涯

完成課程並獲得認證

開始
廣告