parent()和parents()方法的用法和区别:
这两个方法的作用有点类似,都可以取得父级元素,但是并非完全相同,下面结合实例简单介绍一下它们的区别。
先从概念入手:
1.parent()方法可以取得匹配元素的第一级父元素的集合,也就是说它获得并非匹配元素的所有祖先元素,而仅仅是父元素。
2.parents()方法可以取得匹配元素的所有祖先元素(不包含根元素),而不仅仅是第一级父元素。
下面看一段代码实例:
<!DOCTYPE html><html><head><metacharset=" utf-8"><metaname="author"content="http://www.softwhy.com/"/><title>蚂蚁部落</title><styletype="text/CSS">div{width:150px;height:150px;margin:0px auto;background-color:green;}p{width:100px;height:100px;margin:0px auto;background-color:red;}</style><scriptsrc="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script><scripttype="text/javascript">$(document).ready(function() {
$("#bt1").click(function() {
$("span").parent().css("backgroundColor","blue");
})
$("#bt2").click(function() {
$("span").parents().css("backgroundColor","yellow");
})
})</script></head><body><div><p><span>蚂蚁部落</span></p></div><buttonid="bt1">parent方法</button><buttonid="bt2">parents方法</button></body></html>
点击相应的按钮即可查看parent()函数和parents()函数的不同的效果。
原文地址是:http://www.softwhy.com/forum.php?mod=viewthread&tid=5775
更多内容http://www.softwhy.com/jqshili/