【问题标题】:How to get the element number/index between siblings [duplicate]如何获取兄弟姐妹之间的元素编号/索引[重复]
【发布时间】:2011-01-11 03:52:37
【问题描述】:

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

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

使用这样的东西:

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

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

【问题讨论】:

    标签: jquery jquery-selectors


    【解决方案1】:

    您可以为此使用.index()

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

    因为你已经给了 li 的 id,所以不需要带有 ul 的元素选择器。 li 元素可以直接使用 id 选择器。

    【讨论】:

    • 简单有效,谢谢。 :)
    • 最好还是使用类型选择器来提高搜索速度,$("li#selected") 应该比 $("#selected") 快。
    • @shortstick 不使用 id-selectors ('#'),它使用更快的原生函数 getElementByID。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-29
    • 1970-01-01
    • 2020-03-31
    • 1970-01-01
    • 2017-11-19
    相关资源
    最近更新 更多