jQuery的parent()和parents()方法的用法和区别

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

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/

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航