JQuery - using inArray () to find the index of a jQuery object

I have a few divs that I would like to add to an array.

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

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

alert(jQuery.inArray($("#div1"),myArray)); // returns -1
+4
source share
7 answers

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

Instead, you can simply use the selector or other identifying function of the element.

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

However, it really depends on your use case.

+7
source

, ,

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

,

,

var div1 = $('#div1');
var div2 = $('#div2');
var div3 = $('#div3');

var myArray = [ div1, div2, div3 ];

jQuery.inArray( div1 , myArray); // returns 0
+5

.inArray() .

. .

+1

, , jQuery , DOM node. inArray :

var $div1 = $('#div1'), 
    $div2 = $('#div2'), 
    myArray = [ $div1, $div2 ];

alert(jQuery.inArray($div1,myArray));
0

jQuery, $( "# div1" ) jQuery, dom, jQuery, dom. inArray , , inArray.

var arr = [],
    $d1 = $("#d1"),
    $d2 = $("#d2"),
    $d3 = $("#d3");

arr.push($d1, $d2, $d3);

console.log(jQuery.inArray($d3, arr));

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

0

. , , , .

var possiblePositions = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]

function randomSpin(sides) {
 return Math.floor(Math.random() * (sides || 6) ) + 1;
}
var $currentPiece = $('piece.active');
var currentSpot = $currentPiece.attr('spotPosition');
var spin = randomSpin(6) + randomSpin(6);
var nextSpot = currentSpot + spin;

if (possiblePositions.indexOf(nextSpot)) {
    $('#div' + nextSpot).append($currentPiece);
}
0

If you must use pure jQuery to control jQuery Collection, then you can use the jQuery method index(). However, the index returned is the position of the element in dom, not the order in which it was added to the collection. If you need to deal with the order of addition, you better use 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
source

Source: https://habr.com/ru/post/1544535/


All Articles