【发布时间】: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)。
到目前为止,我已经尝试了一些事情:
-
一个基于使用 id 获取列表中对象索引的简单函数。
elem = list.index(0); //To get the first element, but this is not a thing. -
这样的循环:
//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