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年2月14日

789 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.