简体   繁体   English

如何使用jQuery获取特定类的元素的索引,位置数

[英]How to get index, position number of element with certain class with jQuery

I have this markup 我有这个标记

<div class="parent">
    <div class="one"></div>
    <div class="two"></div>
    <div class="one"></div>
    <div class="two"></div>
</div>

My question is: how to get "index" number of element with class two . 我的问题是:如何获得元素的“指数”号带班two I'm not asking of regular index number of element in parent div. 我不问parent div中元素的常规索引号。 I need to know that when i'm clicking at first element with class one that next two element have 0 index or it's first element in this list with class two , and so on. 我需要知道,当我在点击带班第一个元素one ,明年two元有0指数或它的第一个元素在此列表与类two ,依此类推。

I've tried with index() method and eq() and always i have the real index number of this element in parent div. 我已经尝试过使用index()方法和eq()并且总是在parent div中具有该元素的实际索引号。 I hope this is clear, thx for help. 我希望这很清楚,希望有所帮助。

You need to find the elements index in collection of element with sameclass: 您需要在具有相同类的元素集合中找到元素索引:

$('.parent > div').click(function(){
 var index;
 if($(this).is('.one'))
    index = $('.parent > .one').index(this);
 else 
    index = $('.parent > .two').index(this);
});

This should be the faster way to get the index you are looking for. 这应该是获取所需索引的更快方法。

Instead of retrieving all matches, it just counts the number of elements of the same class among previous leafs in your DOM. 它不会检索所有匹配项,而只是计算DOM中先前叶子之间相同类的元素数。

Also, it allows having multiple <div class="parent"> and still work 另外,它允许有多个<div class="parent">并且仍然可以工作

$('.parent div').click(function() {
    // Retrieve clicked element class (one, two)
    var elClass = $(this).attr('class');

    // Retrieve all previous elements that have the same class
    // and count them
    var prevElmts = $(this).prevAll('.' + elClass),
        numPrevElements = prevElmts.length;

    console.log(numPrevElements);
})

Using jquery you can find index of element which have same class name or tag name 使用jQuery,您可以找到具有相同类名或标签名的元素的索引

$(".class_name").on("event_name", function() {
        var index=($(this).index());
        console.log('index : ',index);
});

This may work for you. 这可能对您有用。

var p = $('.parent'),
current = p.filter('.two'),
index = p.index(current);

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

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