找到你要的答案

Q:jQuery select a specific li by giving the index?

Q:jQuery选择特定的李给指标?

I am just trying to highlight the first item in the list:

$('.foo')
    .find('li')[0]
    .css( "background-color", "yellow" );

.find('li') works like I expect it to by highlighting all the li, but I want to be able to select one by giving the index.

https://jsfiddle.net/zAzz8/229/

我只是想突出列表中的第一项:

$('.foo')
    .find('li')[0]
    .css( "background-color", "yellow" );

找(李的)就像我期望它强调所有的力,但我希望能够选择一个由指数。

https://jsfiddle.net/zazz8/229/

answer1: 回答1:

When you do

.find('li')[0]

it gets the native javascript DOM element which does not have access to the jQuery css function.

Use :eq() instead

$('.foo')
    .find('li:eq(0)')
    .css( "background-color", "yellow" );

$('.foo')
  .find('li:eq(0)')
  .css("background-color", "yellow");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class='foo'>
  <ul class="bar">
    <li class="item-i">I</li>
    <li class="item-ii">II</li>
  </ul>
</div>

当你做

.find('li')[0]

它得到本地JavaScript DOM元素不使用jQuery的CSS功能。

用途:eq()相反

$('.foo')
    .find('li:eq(0)')
    .css( "background-color", "yellow" );

$('.foo')
  .find('li:eq(0)')
  .css("background-color", "yellow");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class='foo'>
  <ul class="bar">
    <li class="item-i">I</li>
    <li class="item-ii">II</li>
  </ul>
</div>
answer2: 回答2:

Using [0] is selecting a DOM element rather than a jQuery object. You can't use the .css() function directly on a DOM element. Use .eq() instead to select the list item as a jQuery object

$('.foo')
    .find('li')
    .eq(0)
    .css("background-color", "yellow")

使用[ 0 ]是选择一个DOM元素而不是一个jQuery对象。你不能使用。css()功能直接在DOM元素。使用。eq()相反选择列表项作为一个jQuery对象

$('.foo')
    .find('li')
    .eq(0)
    .css("background-color", "yellow")
jquery