Why doesn't index() working as expected

前端 未结 5 1656
余生分开走
余生分开走 2021-01-22 18:09

HTML:

Div 1
Div 2
Div 3
<
5条回答
  •  醉话见心
    2021-01-22 18:46

    why the output is 4, 6, 8, 10

    $(this).index() returns the index of the element relative to its siblings, not to the selected elements. The br and .divX elements are siblings as well!

    It looks like you want:

    var $tests = $(".test");
    
    $tests.each(function(){
        var i = $tests.index(this);
        alert(i);
    });
    

    or simpler:

    $(".test").each(function(i){
        alert(i);
    });
    

提交回复
热议问题