2011-11-15 46 views
0
<form id="foo"> 
    <input></input> 
    <input></input> 
    <input></input> 
</form> 

我想做的事:選擇元素從列表中通過指數與jQuery

document.getElementById("foo").getElementsByTag("input")[1];

但在jQuery的。我想通過索引選擇#foo下的某個對象。

這是我第一次的猜測,如何做到這一點:

$('#foo input[1]').val("BlahBlah");

我認爲這將是在CSS一樣了。

回答

4

你可以這樣來做:

$('#foo input').eq(1).val("BlahBlah"); 

這會給你的第二個輸入。如果您想要第一個,請將1更改爲0. .eq()函數爲0。

0

我會說:

$($('#foo input')[1]).val("BlahBlah"); 
2
$('#foo :input').eq(1).val('BlahBlah') 
1

您可以使用eq()選擇:

$('#foo input:eq(1)').val("BlahBlah"); 
1

可以使用eq選擇。它接受一個從零開始的索引:

$('#foo input:eq(1)').val('a value'); 
1

使用第n個孩子(n)的僞類是這樣的...

$("#foo input:nth-child(0)").val("BlahBlah"); 
$("#foo input:nth-child(1)").val("BlahBlah"); 
. 
. 
. 
$("#foo input:nth-child(n)").val("BlahBlah"); 
3

在jQuery中有定義爲選擇和使用元素幾個方法從一個(DOM對象)列表。

使用:

var list = $("#foo"); 

你會捕捉整個#foo。如果你爲了簡單起見,你可以通過使用var children = list.children();來獲得孩子(即輸入字段)。但是如果你想要一些看起來更像findElementsByTag的東西,你可以使用var children = list.find('input');(哪一個課程可以是一個班輪,但通常你想再利用的整個列表太)

讓孩子的某些列表的第一個和最後一個項目有一些預定義的功能:

var first = children.first(); 
var last = children.last(); 

要找到你可以使用一個-nth元素http://api.jquery.com/eq/http://api.jquery.com/nth-child-selector/

所以你會得到(注意它的工作只是像0基於索引的數組)

var second = children.eq(1); 

如果你像CSS選擇器樣式越多,你也可以嘗試(注意1開始的索引)

var second_b = $("#foo input:nth-child(2)");