Javascript 如何获取<ul>中<li>的索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5914110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:30:03  来源:igfitidea点击:

How to get the index of an <li> in a <ul>

javascriptjqueryjquery-ui

提问by user695663

Possible Duplicates:
How to get index of <li> element
jQuery - get the index of a element with a certain class

可能的重复项:
如何获取 <li> 元素
的索引 jQuery - 获取具有特定类的元素的索引

I have:

我有:

<ul id="parent">
     <li id="li1">li1</li>
     <li id="li2">li2</li>
     <li id="li3">li3</li>
</ul>

There are some other <ul>and <li>tags elsewhere.

其他地方还有一些其他<ul><li>标签。

I want to get the index of li2which is in the <ul>with id parentusing jQuery

我想使用 jQuery获取带有 id父级li2的索引<ul>

回答by pixelbobby

OLDsimple answer: $('ul#parent li:eq(1)').index()

旧的简单答案:$('ul#parent li:eq(1)').index()

NEW$('#li2').index()

新的$('#li2').index()

回答by Felix Kling

Use .index():

使用.index()

$('#li2').index();

IDs have to be unique so in case they are not in your HTML, you better fix this (e.g. by using classes).

ID 必须是唯一的,以防它们不在您的 HTML 中,您最好解决这个问题(例如,通过使用类)。

回答by Sang Suantak

var index = $("#li2").prevAll().length;  //assuming 0 based index