jQuery 中 $.closest() 和 $.parents() 方法有什麼區別?


jQuery closest 和 parents 方法用於設定或獲取第一個或所有匹配選擇器的祖先元素。讓我們看看下面的區別

jQuery closest() 方法

closest() 方法從當前元素開始,只返回第一個匹配傳遞表示式的祖先元素。此返回的 jQuery 物件包含零個或一個元素。

示例

您可以嘗試執行以下程式碼,瞭解如何使用 jQuery closest 方法 -

線上演示

<!DOCTYPE html>
<html>
<head>
<style>
.myclass * {
    display: block;
    border: 2px solid blue;
    color: red;
    padding: 5px;
    margin:10px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
 $(document).ready(function(){
    $("span").closest("ol").css({"color": "gray", "border": "5px solid maroon"});
 });
</script>
</head>

<body class="myclass">body
  <div style="width:500px;">div
    <ol>ol - This is the third ancestor
    <ol>ol - This is the second ancestor
    <ol>ol - This is the first ancestor
      <li>li - This is the direct parent element
        <span>demo</span>
      </li>
      </ol>
      </ol>
    </ol>  
  </div>
</body>

jQuery parents() 方法

parents() 方法從父元素開始,返回所有匹配傳遞表示式的祖先元素。此方法與 closest() 不同,因為在此方法中,返回的 jQuery 物件包含零個或多個元素。

示例

線上演示

<!DOCTYPE html>
<html>
<head>
<style>
 .myclass * {
    display: block;
    border: 5px solid blue;
    color: red;
    padding: 9px;
    margin: 14px;
 }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
  $(document).ready(function(){
    $("span").parents().css({"color": "green", "border": "4px solid green"});
  });
</script>
</head>

<body class="myclass">body
  <div style="width:600px;">div
    <ol>ol
      <li>li - This is the direct parent element
        <span>demo</span>
      </li>
    </ol>  
  </div>
</body>

</html>

更新於: 2020年2月14日

789 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.