简体   繁体   English

获取基于类的元素的jQuery索引

[英]Get Jquery index of element based on class

I need to find the index of element with class "span": 我需要找到带有“ span”类的元素的索引:

<div>
<div>
    <div class="sd">
        <h2> H2 TEXT </h2>
        <span> SPAN </span>
        <span class="span"> SPAN </span>
    </div>
</div>
</div>

So i did: 所以我做了:

var q = $('div > div > div.sd').find('.span').index();
alert(q)

This alerts "2" but the class is the first and only so it should alert "1". 此警报为“ 2”,但该类是第一个也是唯一的,因此它应警报“ 1”。 Is this because Jquery looks for the tag and not the class? 这是因为Jquery会寻找标签而不是类吗? I googled a lot and searched on stack but all examples include a click event which I don't want. 我在Google上搜索了很多,并在堆栈上进行了搜索,但是所有示例都包含了我不想要的click事件。

Live example: http://jsfiddle.net/jL7dsv5y/ 实时示例: http//jsfiddle.net/jL7dsv5y/

If you apply .index() to a collection, and pass an element to it, it will return the position of that element within the collection. 如果将.index()应用于集合,并将元素传递给它,它将返回该元素在集合中的位置。 This will alert 0 because the .span element within the div is the first of all the .span elements in the document. 这将提醒0 ,因为.span的元素内div是第一次所有的.span的文档中的元素。

 var q = $(".span").index($('div > div > div.sd').find('.span')); alert(q); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <div> <div class="sd"> <h2> H2 TEXT </h2> <span> SPAN </span> <span class="span"> SPAN </span> </div> </div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM