2010-10-01 25 views
1

我怎麼能得到例如所有準備選定的jQuery的元素中的所有鏈接(這)

$("#container li").each(function(){ 
    $("this a").each(function(){ 
     // links inside this li element 
    }); 
}); 

這不起作用,有沒有其他辦法?

回答

6

您可以使用.find()功能:

$('#container li').each(function() { 
    $(this).find('a').each(function() { 
     // links inside this li element 
    }); 
}); 

或避免嵌套的循環,你可以直接選擇鏈接,然後取出,如果需要的家長li

$('#container li a').each(function() { 
    var parentLi = $(this).parent('li'); 
}); 
+0

偏離航向THX! – Remi 2010-10-01 10:22:23

3

或者到達林的建議, jQuery允許你爲選擇器定義一個上下文節點。

所以,你可以這樣做:

var 
    $listItems = $('#container li'), 
    // use $listItems as context 
    $anchors = $('a', $listItems); 
+0

或者,[**稍微直接**](http://jsfiddle.net/b9S4p/):'$('a','#container li')' – 2010-10-01 11:27:10

+0

當然,雖然據我瞭解,這是關於重用元素。你的版本似乎完全擊敗了這個目的。 – Thomas 2010-10-01 11:33:14