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

后端 未结 7 1217
粉色の甜心
粉色の甜心 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/

提交回复
热议问题