jQuery最近和父母方法用于设置或获取与选择器匹配的第一个或所有祖先元素。让我们看看下面的区别:
closest()
方法该closest()
方法从当前元素开始,并且仅返回与传递的表达式匹配的前祖。返回的jQuery对象具有零个或一个元素。
您可以尝试运行以下代码来学习如何使用jQuery最接近的方法-
<!DOCTYPE html> <html> <head> <style> .myclass * { display: block; border: 2px solid blue; color: red; padding: 5px; margin:10px; } </style> <script src="https://cdn.staticfile.org/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>
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://cdn.staticfile.org/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>