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

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

提交回复
热议问题