使用jQuery从索引列表中选择元素
我想要做:
document.getElementById("foo").getElementsByTag("input")[1];
但在jQuery中。 我想通过索引选择#foo下的某个对象。
这是我对如何做到这一点的第一个猜测:
$('#foo input[1]').val("BlahBlah");
我认为它在CSS中也是一样的。
你可以这样做:
$('#foo input').eq(1).val("BlahBlah");
这将为您提供第二个输入。 如果需要第一个,请将1更改为0. .eq()
函数基于0。
在jQuery中,定义了几个方法来选择和使用(DOM对象)列表中的元素。
通过使用:
var list = $("#foo");
你会捕获整个#foo
。 如果你的简单,你可以通过使用var children = list.children();
获得孩子(即输入字段var children = list.children();
但是如果你想要一些看起来更像findElementsByTag的东西,你可以使用var children = list.find('input');
(哪个可以是一个class轮,但通常你也想重新使用整个列表)
要获取某个孩子列表的第一个和最后一个项目,有一些预定义的函数:
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");