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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:25:19  来源:igfitidea点击:

Get an element by index in jQuery

jquerydomget

提问by Rama Rao M

I have an unordered list and the index of an litag in that list. I have to get the lielement 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 cssfunction, use the last...

DOM 对象没有css功能,使用最后一个...

$('ul li').eq(index).css({'background-color':'#343434'});

docs:

文档:

.get(index)Returns: Element

.get(index)返回:元素

.eq(index)Returns: jQuery

.eq(index)返回: jQuery

回答by Christofer Eliasson

You can use jQuery's .eq()method to get the element with a certain index.

您可以使用 jQuery 的.eq()方法来获取具有特定索引的元素。

$('ul li').eq(index).css({'background-color':'#343434'});

回答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-typepseudo-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>