我为此寻找了很多解决方案,但令人惊讶的是找不到任何东西。也许我只是没有搜索正确的词。我发现了一堆关于按元素获取索引的问题,但我需要相反。
我正在尝试使用 javascript 和 jquery 通过它在列表中的索引来获取有序列表中的元素。例如,如果我有这个列表:
<ol>
<li>Zero</li>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ol>
我希望能够Zero
通过索引 0 获取第一个 ( ),或者One
通过索引 1 获取第二个 ( )。
到目前为止,我已经尝试了几件事:
一个简单的函数,基于使用 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;
那么有没有办法做到这一点?谢谢。