Why doesn't index() working as expected

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

HTML:

Div 1
Div 2
Div 3
<
相关标签:
5条回答
  • 2021-01-22 18:40

    Easy fix - .each supports index :

    $(".test").each(function(idx){
        alert(idx);
    });
    
    0 讨论(0)
  • 2021-01-22 18:43

    You have to make it relative to what you're testing against. Use:

    $(".test").each(function(){
        var i = $('.test').index($(this));
        console.log(i);
    });
    

    jsFiddle example

    Per the docs on .index():

    If .index() is called on a collection of elements and a DOM element or jQuery object is passed in, .index() returns an integer indicating the position of the passed element relative to the original collection.

    0 讨论(0)
  • 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);
    });
    
    0 讨论(0)
  • 2021-01-22 18:46

    What you want to do is this:

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

    .index() returns the index relative to its siblings.

    0 讨论(0)
  • 2021-01-22 18:48

    index() gives index of element with respect to its siblings. The first div with class text is 5th element and has index 4, br is at 5 index and next div with class test has index 6 and so on. We can check the indexes of each element by the following demo

    Live Demo

    $("#parent1 *").each(function () {
        alert("TagName >> " + this.tagName + ", Index >> " + $(this).index() + ", Text " + $(this).text());
    });
    

    If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements, Reference.

    0 讨论(0)
提交回复
热议问题