【问题标题】:Get an element by index in jQuery在jQuery中按索引获取元素
【发布时间】:2012-04-10 20:47:11
【问题描述】:

我有一个无序列表和该列表中 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>

【问题讨论】:

  • 您在此处使用的两种方式返回 dom 元素而不是 jQuery 对象,因此对 .css 的调用将无法对它们起作用。 Darius 在下面使用 eq 的答案就是你想要的。

标签: jquery dom get


【解决方案1】:

您可以使用eq method or selector:

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

【讨论】:

  • 你可以使用$('ul li').eq(index).css({'background-color':'#343434'});使选择器更简单
  • 但在大多数浏览器中,选择器$('ul').find('li') 更快。 [1, 2]
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:
    $(...)[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) 返回:元素

    .eq(index) 返回:jQuery

    【讨论】:

      【解决方案4】:

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

      <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>
      

      还有其他selectors,您可以使用 jQuery 来匹配您需要的任何元素。

      【讨论】:

        【解决方案5】:

        你可以跳过 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>
        

        【讨论】:

          猜你喜欢
          • 2014-12-15
          • 1970-01-01
          • 1970-01-01
          • 2012-09-06
          • 2012-02-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多