jQuery 如何获取兄弟姐妹之间的元素编号/索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4654028/
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-26 17:38:50  来源:igfitidea点击:

How to get the element number/index between siblings

jqueryjquery-selectors

提问by MacMac

How can you get the child number of the selected element, e.g.

如何获取所选元素的子编号,例如

<ul>
    <li>First child</li>
    <li>Second</li>
    <li id="selected">Third child</li>
    <li>Fourth child</li>
</ul>

Using something like this:

使用这样的东西:

$('#selected').childNumber();

That should return "3" for it's parent wrap, regarding the child number.

关于子编号,它的父包装应该返回“3”。

回答by rahul

You can use .index()for this.

您可以.index()为此使用。

var selectedIndex = $("#selected").index() + 1;

Since you have given an id for the li there is no need for the element selector with ul. You can directly use the id selector for the li element.

由于您已经为 li 指定了 id,因此不需要带有 ul 的元素选择器。您可以直接为 li 元素使用 id 选择器。