【问题标题】:Get Element in HTML Ordered List by Index Using Javascript使用 Javascript 按索引获取 HTML 有序列表中的元素
【发布时间】:2013-06-30 03:45:29
【问题描述】:

我为此寻找了很多解决方案,但令人惊讶的是找不到任何东西。也许我只是没有搜索正确的词。我发现了一堆关于按元素获取索引的问题,但我需要相反的。

我正在尝试使用 javascript 和 jquery 通过它在列表中的索引来获取有序列表中的元素。例如,如果我有这个列表:

<ol>
  <li>Zero</li>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ol>

我希望能够通过索引 0 获取第一个 (Zero),或者通过索引 1 获取第二个 (One)。

到目前为止,我已经尝试了一些事情:

  1. 一个基于使用 id 获取列表中对象索引的简单函数。

    elem = list.index(0); //To get the first element, but this is not a thing.
    
  2. 这样的循环:

    //elem is the element I am currently at.
    //Starting at the last element and going to the first.
    var elem = list.getLastChild(); //But list.getLastChild() is apparently
    //not a thing although it is here ([w3c link][1]).
    
    //Start at 0 and go to the index
    //(may/may not need the = before num, but I think I do)
    for(var i=0; i<=num; i++){
        //Set elem to it's previous sibling
    elem = elem.getPreviousSibling(); //getPreviousSibling is probably not a thing as
        //well but I couldn't get that far before it broke anyway.
    }
    
    //Return the element at the index
    return elem;
    

那么有没有办法做到这一点? 谢谢。

【问题讨论】:

    标签: javascript jquery html indexing html-lists


    【解决方案1】:

    有很多方法可以做到这一点。您可以使用 :eq 选择器。像这样?

    var $lis = $('ol li');
    
    for(var i=0; i < $lis.length; i++)
    {
        alert($('ol li:eq(' + i + ')').text());
    }
    

    Demo

    所以,因为这是零索引。你可以这样做:$('ol li:eq(0)') 获取第一个元素。 也可以使用css、nth-childnth-of-type选择器:

      alert($('ol li:nth-child(1)').text()); // This starts with 1 index, non-zero indexed.
    

    【讨论】:

    • 这个答案给了我我想要的东西(for循环中的部分)。 @TGH 给了我别的东西。我不知道为什么,但确实如此。
    • @maptwo3 你是什么意思?您正在使用第 n 个孩子....?在这种情况下,在循环中执行 +1 如果您使用 nth-child 也需要小心,尤其是有不同类型的兄弟姐妹。此类案件将寻求救援。但你总是可以使用:eq
    • 我真的不确定我的意思。我对网络开发很陌生。当我打印它们时,它们给了我不同的输出。你的给了我实际的元素,而他的给了我别的东西。你的工作,而他没有(我也做了+1 部分)。 :eq 部分对我有用。
    • 我刚刚在div 上测试了这个,当我打印它们时,:eq 方式给了我div,而 nth-child 给了我prevObject(这些是打印的第一个字无论如何)。
    • @maptwo3 好的。我建议:eq 但第n 个孩子在您的场景中也应该可以正常工作,可能i+1 部分没有用括号包裹。 jsfiddle.net/fpZu4
    【解决方案2】:

    你可以使用 JQuery:

    $("ol li:nth-child(1)")
    $("ol li:nth-child(n)")
    

    http://api.jquery.com/nth-child-selector/

    【讨论】:

    • 它不是零索引的。它是 1 索引/
    • 是的,刚刚意识到。再次更新:-)
    • 酷。给我一个 +1 .. :)
    猜你喜欢
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    • 2015-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-15
    • 1970-01-01
    相关资源
    最近更新 更多