在 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-02-14

785 次瀏覽

立即開啟您的 職業生涯

完成此課程並獲得認證

開始學習
廣告