简体   繁体   English

使用jQuery从列表中选择元素

[英]Select Element From List by Index with jQuery

<form id="foo">
    <input></input>
    <input></input>
    <input></input>
</form>

I want to do: 我想要做:

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

But in jQuery. 但是在jQuery中。 I want to select a certain object under #foo by an index. 我想通过索引选择#foo下的某个对象。

This is my first guess as to how to do this: 这是我关于如何执行此操作的第一个猜测:

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

I think it would be the same in CSS too. 我认为CSS也一样。

You could do it this way: 您可以这样进行:

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

That will give you the second input. 这将为您提供第二个输入。 If you want the first, change the 1 to a 0. The .eq() function is 0 based. 如果需要第一个,请将1更改为.eq()函数基于0。

In jQuery there are a couple of methods defined to select and use elements from a (DOM objects) list. 在jQuery中,定义了两种方法来选择和使用(DOM对象)列表中的元素。

By using: 通过使用:

var list = $("#foo");

You would capture the entire #foo . 您将捕获整个#foo If your in for simplicity you could get the children (ie the input fields) by using var children = list.children(); 如果为了简单起见,可以使用var children = list.children();来获得子代(即输入字段var children = list.children(); But if you want something that seems a bit more like findElementsByTag, you could use var children = list.find('input'); 但是,如果您想要看起来更像findElementsByTag的东西,则可以使用var children = list.find('input'); (Which ofcourse could be a one liner, but usually you want to re-use the entire list too) (当然,这可能只是一个班轮,但通常您也想重用整个列表)

To get the first and last item of a certain list of children there are some predefined functions: 为了获得某些子项列表的第一项和最后一项,有一些预定义的函数:

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

To find an -nth element you can use http://api.jquery.com/eq/ or http://api.jquery.com/nth-child-selector/ 要查找-nth元素,可以使用http://api.jquery.com/eq/http://api.jquery.com/nth-child-selector/

So you would get (note it works just like an array with 0-based index) 因此,您将获得(请注意,它的工作方式就像具有从0开始的索引的数组一样)

var second = children.eq(1);

If you like CSS selector style more you can also try (note the 1-based index) 如果您更喜欢CSS选择器样式,也可以尝试(请注意从1开始的索引)

var second_b = $("#foo input:nth-child(2)");
$('#foo :input').eq(1).val('BlahBlah')

您可以使用eq()选择器:

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

You can use the eq selector. 您可以使用eq选择器。 It receives a zero-based index: 它接收从零开始的索引:

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

Use nth-child(n) pseudo class like this ... 像这样使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM