【问题标题】:How to get index, position number of element with certain class with jQuery如何使用 jQuery 获取具有特定类的元素的索引、位置编号
【发布时间】:2019-01-23 22:51:20
【问题描述】:

我有这个标记

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

我的问题是:如何获取类two 的元素的“索引”数。我不是在询问parent div 中元素的常规索引号。我需要知道,当我单击类one 的第一个元素时,下一个two 元素的索引为0,或者它是该列表中类two 的第一个元素,依此类推。

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

【问题讨论】:

  • 必须在 jQuery 中?

标签: javascript jquery html


【解决方案1】:

您需要在具有相同类的元素集合中找到元素索引:

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

【讨论】:

    【解决方案2】:

    这应该是获取您要查找的索引的更快方法。

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

    此外,它允许拥有多个 &lt;div class="parent"&gt; 并且仍然可以工作

    $('.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);
    })
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

        这可能对你有用。

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-05-11
          • 2012-01-23
          • 1970-01-01
          • 2012-05-15
          • 2013-09-06
          • 2017-04-15
          • 2012-09-06
          • 1970-01-01
          相关资源
          最近更新 更多