parent,parents和closest

1.parent

parent() 获得当前匹配元素集合中每个元素的父元素,使用选择器进行筛选是可选的。

 1 <ul id="menu" style="100px;">
 2         <li>Start</li>
 3     <li>
 4         <ul>
 5             <li>
 6                 <ul>
 7                     <li><a href="#">Home</a></li>
 8                 </ul>
 9                 
10             </li>
11             <li>middle</li>
12         </ul>
13     </li>
14     <li>End</li>
15 </ul>
1 $("#menu a").click(function() {
2        $(this).parent("ul").css("background", "yellow");//无效
3         $(this).parent("li").parent("ul").css("background", "yellow");
4 }

第二行是无效的。因为a的父级是li而不是ul.第三行会使Home外的ul背景变黄色。

2.parents

parents() 获得当前匹配元素集合中每个元素的祖先元素,使用选择器进行筛选是可选的。

1 $("#menu a").click(function() {
2        $(this).parents("ul").css("background", "yellow");}

整个背景都会变黄。

3.closest

closest() 方法获得匹配选择器的第一个祖先元素,从当前元素开始沿 DOM 树向上。

1 $("#menu a").click(function() {
2        $(this).parent("ul").css("background", "yellow");  
3 }

只有home外的ul的背景变黄

三者联系:

1 $("#menu a").click(function() {
2        $(this).parent("li").parent("ul").css("background", "yellow");   
3        $(this).parents("ul").eq(0).css("background", "yellow");  
4        $(this).closest("ul").css("background", "yellow");  
5        
6 });

以上2 3 4行达到的效果是一致的。

原文地址:https://www.cnblogs.com/MissBean/p/bianli.html