2014-05-12 105 views
1

我試圖選擇所有具有「findme」類的元素,並從那些獲取它們附近的選擇。 http://jsfiddle.net/R93md/1/jquery在遍歷DOM時選擇多個

具體地說我試圖

$(".findme").parent().prev().first(); 

然後一旦我有我打算做一個

.each(function(){doSomething(this);}) 

到每個選擇的所有選擇。我堅持得到選擇,因爲它似乎我永遠不會下降,並檢索跨度的內容。

+0

我覺得ere也是'.closest()'。如果你想獲得附近的元素,這個名字聽起來很有希望。 – GolezTrol

回答

4
$(".findme").closest("td").find("select").each(function() { 
    doSomething(this); 
}); 
1

我先搶父<td>元素,然後用find()像這樣

$('.findme').parents('td').find('select').each(function(){ 
    ... 
}); 

http://jsfiddle.net/JYGK3/

編輯: 在其他的答案審查在這裏,我已經得出結論,你應該使用closest()而不是parents()。如果表嵌套,則可能會產生不需要的結果。

http://jsfiddle.net/JYGK3/1

1

您可以使用.closest()上去的共同<td>,然後.find()去從那裏向下尋找鄰近<select>

$(".findme").each(function() { 
    var select = $(this).closest("td").find("select"); 
    // now do what you want to with the neighboring select object 
    // here you have access to both this which is the findme object 
    // and select which is the select object 
}); 
1

我認爲你應該遵循這樣的:

$('.findme').each(function(){ 
    var el = $(this).closest('td').find('select'); 
    dosomething(el); 
});