[英]Select Element From List by Index with jQuery
<form id="foo">
<input></input>
<input></input>
<input></input>
</form>
我想要做:
document.getElementById("foo").getElementsByTag("input")[1];
但是在jQuery中。 我想通過索引選擇#foo下的某個對象。
這是我關於如何執行此操作的第一個猜測:
$('#foo input[1]').val("BlahBlah");
我認為CSS也一樣。
您可以這樣進行:
$('#foo input').eq(1).val("BlahBlah");
這將為您提供第二個輸入。 如果需要第一個,請將1更改為.eq()
函數基於0。
在jQuery中,定義了兩種方法來選擇和使用(DOM對象)列表中的元素。
通過使用:
var list = $("#foo");
您將捕獲整個#foo
。 如果為了簡單起見,可以使用var children = list.children();
來獲得子代(即輸入字段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)");
$('#foo :input').eq(1).val('BlahBlah')
您可以使用eq()選擇器:
$('#foo input:eq(1)').val("BlahBlah");
您可以使用eq
選擇器。 它接收從零開始的索引:
$('#foo input:eq(1)').val('a value');
像這樣使用nth-child(n)偽類...
$("#foo input:nth-child(0)").val("BlahBlah");
$("#foo input:nth-child(1)").val("BlahBlah");
.
.
.
$("#foo input:nth-child(n)").val("BlahBlah");
我會說 :
$($('#foo input')[1]).val("BlahBlah");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.