標籤:jquery children
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// #1anchors.children();// #2$('> *', anchors);// #3anchors.find('> *')
當然,children()函數也接受selector的參數。例如
$('#content').children('p')
更多內容,請參考jQuery -> 擷取後代元素的三種方法