如何在 jQuery 中選擇一個父元素中的所有子代(任何級別)?


要從 jQuery 中的父節點選擇所有子代,請使用 find() 方法。您可以嘗試執行以下程式碼來選擇任何級別的所有子代:

示例

線上演示

<!DOCTYPE html>
<html>
  <head>
  <style>
   .myclass * {
     display: block;
     border: 2px solid lightgrey;
     color: lightgrey;
     padding: 5px;
     margin: 15px;
   }
  </style>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script>
  $(document).ready(function(){
    $('ul').find('*').css({"color": "red", "border": "2px solid green"});
  });
  </script>
</head>
<body>
<div class="myclass">
  <div style="width:400px;">div - great-grandparent
  <ul>ul
   <li>li- child - level 1
     <ul>ul- child - level 2
       <li>li- child - level 3</li>
       <li>li- child - level 3</li>
     </ul>  
   </li>
  </ul>  
 </div>
</div>

</body>
</html>

更新於:2020 年 6 月 20 日

856 次觀看

開啟您的 職業

透過完成課程獲得認證

開始
廣告