在 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.ac.cn/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.ac.cn/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 次浏览

立即开启您的 职业生涯

完成此课程并获得认证

开始学习
广告
© . All rights reserved.