jQuery - using inArray() to find index of jQuery object

后端 未结 7 1215
粉色の甜心
粉色の甜心 2021-01-19 02:09

I have a few divs that I\'d like to put into an array.

When I try to use jQuery.inArray(), my div (as a jQuery object) isn\'t found. Why not?

var my         


        
相关标签:
7条回答
  • 2021-01-19 02:27

    You are not storing any references to the jQuery objects, $("#div1") will return a new jQuery object containing your dom element, you are comparing two different jQuery objects containing the same dom element. inArray will work just fine if you are using the same reference in the array as when you do use the inArray method.

    var arr = [],
        $d1 = $("#d1"),
        $d2 = $("#d2"),
        $d3 = $("#d3");
    
    arr.push($d1, $d2, $d3);
    
    console.log(jQuery.inArray($d3, arr));
    

    or see http://jsfiddle.net/EQQ96/2/

    0 讨论(0)
  • 2021-01-19 02:29

    It's probably because each invocation of the jQuery constructor results in a new instance referring to the same DOM node. What would effectively allow you to demonstrate inArray looks something like this:

    var $div1 = $('#div1'), 
        $div2 = $('#div2'), 
        myArray = [ $div1, $div2 ];
    
    alert(jQuery.inArray($div1,myArray));
    
    0 讨论(0)
  • 2021-01-19 02:30

    You can't use .inArray() for object comparison by content.

    I like the approach outlined here. It's very clean.

    0 讨论(0)
  • 2021-01-19 02:36

    Two objects are never the same, so when you do

    var object1 = $('#div1');
    var object2 = $('#div1');
    

    even if you have the same element, the objects are not the same

    If you use the same object, it works

    var div1 = $('#div1');
    var div2 = $('#div2');
    var div3 = $('#div3');
    
    var myArray = [ div1, div2, div3 ];
    
    jQuery.inArray( div1 , myArray); // returns 0
    
    0 讨论(0)
  • 2021-01-19 02:36

    If you were to use purely jQuery to manipulate the jQuery Collection then you can use the jQuery index() method. However, the index returned is the position of the element in the dom, not the order in which it was added to the collection. If you need to deal with the order of adding then you're better of using selector strings rather than jQuery Collection:

    var myArray = $([]).add( "#div4" ).add( "#div3" ).add( "#div1" ).add( '#div2' );
    console.log( myArray.index( $('#div3') ) ); //Output: 2
    

    JS FIDDLE DEMO

    0 讨论(0)
  • 2021-01-19 02:37

    $ creates a new jQuery collection object each time, so var a = $("div"), b = $("div") will actually be two different objects that don't equal each other.

    Instead you can just use the selectors or some other identifying feature of the element.

    var myArray = ["#div1", "#div2", "#div3"];
    

    However it really depends on your use case.

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