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

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

本文关键字:元素 位置 编号 jQuery 何使用 获取 索引      更新时间:2023-09-26

我有这个标记

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

我的问题是:如何获得类two元素的"索引"数。我不要求在parentdiv中元素的常规索引数。我需要知道,当我点击第一个元素与类one,下一个two元素有0索引或它的第一个元素在这个列表与类two,等等。

我已经尝试过index()方法和eq(),并且总是我在parentdiv中有此元素的真实索引号。我希望这是清楚的,谢谢帮助。

您需要在具有samecclass的元素集合中查找元素索引:

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

这应该是获得您正在寻找的索引的更快方法。

它不检索所有匹配项,而只是计算DOM中先前叶子中相同类的元素数量。

此外,它允许有多个<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);
})

使用jquery可以找到具有相同类名或标签名的元素的索引

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

这可能对你有用。

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