javascript - 使用 Javascript 按索引获取 HTML 有序列表中的元素

标签 javascript jquery html indexing html-lists

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

我正在尝试使用 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;
    

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

最佳答案

有很多方法可以做到这一点。您可以使用: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.

关于javascript - 使用 Javascript 按索引获取 HTML 有序列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17386933/

相关文章:

javascript - 设置数据属性后无法获取数据属性

javascript - Jquery:ajax循环

javascript - 如何自定义 ionic 选择和 ionic 选项菜单( ionic )

java - 如何使用Jsoup通过ID查找元素?

javascript - 使用 JS 将类应用于父元素

php - 使用 PHP 上传多张图片

javascript - 在 webpack 配置中提供模块定义

javascript - 在JS中,如何判断一个字符串是否包含在另一个字符串中?

javascript - 如果元素不包含 "*",则使用 jQuery 将 "*"添加到标签

php - 使用jquery修改服务器端函数