如何从项目列表中获取特定的 jQuery 项目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7514448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get a specific jQuery item from a list of items?
提问by Guffa
I have this:
我有这个:
<ul>
<li>first</li>
<li>second</li>
<li>third</li>
<li>fourth</li>
</ul>
Then I select it all with jQuery: $('ul').find('li');
or $('ul li');
然后我用 jQuery 全选:$('ul').find('li');
或者$('ul li');
How can I, from those two jQuery selectors get the, for instance only second li, or third, and to leave first and fourt alone?
我怎样才能从这两个 jQuery 选择器中获得,例如只有第二个 li 或第三个,而单独留下第一个和第四个?
I thought it might work with:
我认为它可能适用于:
$('myselector').get(indexNumber); // however, it won't work.
Any ideas for this issue? Thanks.
对这个问题有什么想法吗?谢谢。
回答by Guffa
The get
method returns the DOM element, so then you would have to wrap it inside a new jQuery object.
该get
方法返回 DOM 元素,因此您必须将其包装在一个新的 jQuery 对象中。
You can use the eq
method:
您可以使用以下eq
方法:
var j = $('ul li').eq(1); // gets the second list item
回答by Andrius
Use :eq() Selector. For for example, for second element use:
使用:eq() 选择器。例如,对于第二个元素使用:
$("ul li:eq(1)");
回答by Chetan
$('li').get(0) will return plain DOM element. you cannot call jQuery methods on same.
$('li').get(0) 将返回纯 DOM 元素。你不能在同一个上调用 jQuery 方法。
回答by Manuel van Rijn
I would try:
我会尝试:
$("ul li:nth-child(2)")
回答by Rafay
you can use nth-child
您可以使用 nth-child
$("ul li:nth-child(2)") //this will select second child because it is 1 based index
here is a fiddle http://jsfiddle.net/xyyWh/
这是一个小提琴http://jsfiddle.net/xyyWh/