通过在jQuery中索引获取元素
我有一个无序列表和列表中的li标签的索引。 我必须通过使用该索引来获取li元素并更改其背景颜色。 这可能没有循环整个列表? 我的意思是,有什么方法可以实现这个function? 
这是我的代码,我相信会工作…
 <script> var index = 3; </script> <ul> <li>India</li> <li>Indonesia</li> <li>China</li> <li>United States</li> <li>United Kingdom</li> </ul> <script> //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> 
	
 $(...)[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对象没有css函数,使用最后一个… 
 $('ul li').eq(index).css({'background-color':'#343434'}); 
文档:
  .get(index) 返回:Element 
- 说明:检索由jQuery对象匹配的DOM元素。
- 请参阅: https : //api.jquery.com/get/
  .eq(index) 返回:jQuery 
- 说明:将匹配元素的集合减less到指定索引处的元素。
- 请参阅: https : //api.jquery.com/eq/
 您可以使用jQuery的.eq()方法来获取具有特定索引的元素。 
 $('ul li').eq(index).css({'background-color':'#343434'}); 
您可以使用eq方法或select器 :
 $('ul').find('li').eq(index).css({'background-color':'#343434'}); 
 还有另外一种通过CSS在jQuery中获取元素的方法:nth-of-type -class: 
 <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> 
还有其他的select器 ,你可以使用jQuery来匹配你需要的任何元素。
你可以跳过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>