jQuery提供了很多方法来获取一个元素的direct descendant(直接后代)。
最简单的方式是使用direct descendant combinator (>)
例如,如果要获取如下html代码中<div id="content">的直接孩子节点中的a元素,就可以直接使用
> 符号
<body> <div id="content"> <a href="http://www.jquery.com">jQuery</a> <p> <a href="http://blog.csdn.net/feelang">jQuery tutorial</a> </p> </div> </body>
使用selector获取
$('content > a');
当然,也可以使用带两个参数的jQuery函数
$('> a', ‘#content');
也可以链式调用jQuery的api
$('#content').children();
这三个方法都是等价的,但是$(‘#content‘).children()与$(‘content > a‘)的区别在于前者的查询速度要大于后者。
从表面上看解析selector必然要花费一些时间,但是这种优势并不是绝对的,具体还要取决与浏览器的内部实现。
但是使用在下面这种情况下,使用children()肯定是有优势的。
var anchors = $('#content') // Getting all direct children of all anchor elements // can be achieved in three ways // #1 anchors.children(); // #2 $('> *', anchors); // #3 anchors.find('> *')
当然,children()函数也接受selector的参数。例如
$('#content').children('p')
更多内容,请参考jQuery -> 获取后代元素的三种方法
jQuery -> 获取孩子节点,布布扣,bubuko.com
时间: 2024-12-27 08:47:16