jQuery 在jQuery中按索引获取元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9887534/
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
Get an element by index in jQuery
提问by Rama Rao M
I have an unordered list and the index of an li
tag in that list. I have to get the li
element by using that index and change its background color. Is this possible without looping the entire list? I mean, is there any method that could achieve this functionality?
我有一个无序列表和该列表中li
标签的索引。我必须li
使用该索引获取元素并更改其背景颜色。这可能不循环整个列表吗?我的意思是,有没有什么方法可以实现这个功能?
Here is my code, which I believe would work...
这是我的代码,我相信它会起作用......
<script type="text/javascript">
var index = 3;
</script>
<ul>
<li>India</li>
<li>Indonesia</li>
<li>China</li>
<li>United States</li>
<li>United Kingdom</li>
</ul>
<script type="text/javascript">
// I want to change bgColor of selected li element
$('ul li')[index].css({'background-color':'#343434'});
// Or, I have seen a function in jQuery doc, which gives nothing to me
$('ul li').get(index).css({'background-color':'#343434'});
</script>
回答by gdoron is supporting Monica
$(...)[index] // gives you the DOM element at index
$(...).get(index) // gives you the DOM element at index
$(...).eq(index) // gives you the jQuery object of element at index
DOM objects don't have css
function, use the last...
DOM 对象没有css
功能,使用最后一个...
$('ul li').eq(index).css({'background-color':'#343434'});
docs:
文档:
.get(index)
Returns: Element
.get(index)
返回:元素
- Description: Retrieve the DOM elements matched by the jQuery object.
- See: https://api.jquery.com/get/
- 描述:检索 jQuery 对象匹配的 DOM 元素。
- 见:https: //api.jquery.com/get/
.eq(index)
Returns: jQuery
.eq(index)
返回: jQuery
- Description: Reduce the set of matched elements to the one at the specified index.
- See: https://api.jquery.com/eq/
- 描述:将一组匹配元素减少到指定索引处的元素。
- 见:https: //api.jquery.com/eq/
回答by Christofer Eliasson
回答by Darius M.
You can use the eq method or selector:
您可以使用eq 方法或选择器:
$('ul').find('li').eq(index).css({'background-color':'#343434'});
回答by Yury Fedorov
There is another way of getting an element by index in jQuery using CSS :nth-of-type
pseudo-class:
还有另一种使用 CSS:nth-of-type
伪类在 jQuery 中通过索引获取元素的方法:
<script>
// css selector that describes what you need:
// ul li:nth-of-type(3)
var selector = 'ul li:nth-of-type(' + index + ')';
$(selector).css({'background-color':'#343434'});
</script>
There are other selectorsthat you may use with jQuery to match any element that you need.
还有其他选择器可以与 jQuery 一起使用来匹配您需要的任何元素。
回答by Adam H
You could skip the jquery and just use CSS style tagging:
您可以跳过 jquery 并使用 CSS 样式标记:
<ul>
<li>India</li>
<li>Indonesia</li>
<li style="background-color:#343434;">China</li>
<li>United States</li>
<li>United Kingdom</li>
</ul>