在jQuery中通过索引获取元素

Ram*_*o M 107 jquery dom get

我有一个无序列表和该列表中的li标记索引.我必须li通过使用该索引并更改其背景颜色来获取元素.这可能不循环整个列表吗?我的意思是,有没有什么方法可以实现这个功能?

这是我的代码,我相信它会起作用......

<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>
Run Code Online (Sandbox Code Playgroud)

gdo*_*ica 239

$(...)[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
Run Code Online (Sandbox Code Playgroud)

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

$('ul li').eq(index).css({'background-color':'#343434'});
Run Code Online (Sandbox Code Playgroud)

文档:

.get(index) 返回:元素

.eq(index) 返回:jQuery


Chr*_*son 18

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

$('ul li').eq(index).css({'background-color':'#343434'});
Run Code Online (Sandbox Code Playgroud)


Dar*_* M. 11

您可以使用eq方法或选择器:

$('ul').find('li').eq(index).css({'background-color':'#343434'});
Run Code Online (Sandbox Code Playgroud)


Yur*_*rov 5

:nth-of-type在 jQuery 中还有另一种使用 CSS伪类通过索引获取元素的方法:

<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>
Run Code Online (Sandbox Code Playgroud)

您还可以将其他选择器与 jQuery 一起使用来匹配您需要的任何元素。