【问题标题】:How to get index of elem inside a container based on similar classes?如何根据类似的类获取容器内元素的索引?
【发布时间】:2014-09-12 03:43:41
【问题描述】:

我正在尝试根据子对象的相似类而不是 tag 名称来计算对象的 index 值。

认为type_atype_b 元素之间有一个分隔容器。我写了 index 值,我想得到,但找不到解决这个问题的方法。

Here is jsFiddle.

html:

<div class="container">
    <span class="type_a">0</span>
    <span class="type_a">1</span>
    <span class="type_b">0</span>
    <span class="type_a">2</span>
    <span class="type_b">1</span>
    <span class="type_b active">2</span>
    <span class="type_a">3</span>
    <span class="type_a">4</span>
    <span class="type_b">3</span>
</div>

jQuery:

$('.container .type_b').each(function(index) {
    if ( $(this).hasClass('active') ) {
        console.log($(this).index());
    }
});

【问题讨论】:

    标签: javascript jquery html indexing each


    【解决方案1】:

    已解决:

    $('.container .type_b').each(function(index) {
        if ( $(this).hasClass('active') ) {
            console.log(index);
        }
    });
    

    【讨论】:

      【解决方案2】:

      另一种解决方案:

      console.log($('.container .type_b').index($('.active')));
      

      将记录正确的索引。

      【讨论】:

      • 非常好的和简短的解决方案+1来自我的伙伴(:
      猜你喜欢
      • 2018-06-01
      • 2018-08-28
      • 2020-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多