获取UL中的元素索引 [英] Get Index Of Element Within UL

查看:56
本文介绍了获取UL中的元素索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用jQuery,我希望能够获取包含的锚标记的HREF等于"#All"的li的索引. (在这种情况下,正确的结果将是3)

<div id="tabs">
    <ul>
        <li><a href="#CPU"><span>CPU</span></a></li>
        <li><a href="#Pickup"><span>Pickup</span></a></li>
        <li><a href="#Breakfix"><span>Breakfix</span></a></li>
        <li><a href="#All"><span>All</span></a></li>
    </ul>
</div>

我尝试过:

$("#tabs ul").index($("li a[href='#All']"))

...没有运气.我在做什么错了?

解决方案

这应该做到:

var index = $("#tabs ul li").index($("li:has(a[href='#All'])"));

  • 您正在选择所有<ul>而不是要从中获取索引的所有<li>.
  • 您必须使用:has选择器来检查<li>元素:是否与所需链接,否则匹配的元素将是<a>本身而不是<li>.

通过上述测试,由于索引从0开始,它给了我正确的答案3. /p>

Using jQuery, I'd like to be able to get the index of the li where the contained anchor tag's HREF equals "#All". (In this case the correct result would be 3)

<div id="tabs">
    <ul>
        <li><a href="#CPU"><span>CPU</span></a></li>
        <li><a href="#Pickup"><span>Pickup</span></a></li>
        <li><a href="#Breakfix"><span>Breakfix</span></a></li>
        <li><a href="#All"><span>All</span></a></li>
    </ul>
</div>

I have tried:

$("#tabs ul").index($("li a[href='#All']"))

...with no luck. What am I doing wrong?

解决方案

This should do it:

var index = $("#tabs ul li").index($("li:has(a[href='#All'])"));

  • You were selecting all <ul> instead of all <li>s you wanted to get the index out of.
  • You have to check if the <li> element :has a link with what you want by using the :has selector, otherwise the matched element will be the <a> itself instead of the <li>.

Tested the above and it gives me the correct answer, 3, as the index is 0-based.

这篇关于获取UL中的元素索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆