Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
902 views
in Technique[技术] by (71.8m points)

jquery - Get Index Of Element Within UL

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...