I am having issues understanding why my jQuery index() function is not performing the way I expect it to. Perhaps I’m not understanding this. Let me show you.
I set up a new array. We’ll use this later:
var mySources = new Array();
I have 5 images on my page:
<div id="homeSlides">
<img src="../images/homeImages/00.jpg" width="749" height="240" alt="myAltTag" />
<img src="../images/homeImages/01.jpg" width="749" height="240" alt="myAltTag" />
<img src="../images/homeImages/02.jpg" width="749" height="240" alt="myAltTag" />
<img src="../images/homeImages/03.jpg" width="749" height="240" alt="myAltTag" />
<img src="../images/homeImages/04.jpg" width="749" height="240" alt="myAltTag" />
I put them all in an jQuery object, like this:
var myImages = $("#homeSlides img");
Now, for each one, I extract the src attribute and push it into the mySources array like this:
$(myImages).each( function(index) {
mySources[index] = $(this).attr('src');
});
Now, I will run the array to the FireBug console to make sure it worked.
This…
console.log(mySources);
…returns this…
["../images/homeImages/00.jpg", "../images/homeImages/01.jpg", "../images/homeImages/02.jpg", "../images/homeImages/03.jpg", "../images/homeImages/04.jpg"]
…which is what I expect.
Now I do this:
var myVar = $(myImages).eq(2).attr('src');
Tracing that variable now…
console.log(myVar);
…returns this…
../images/homeImages/02.jpg
But then when I do this…
console.log('Index of ' + myVar + " is: " + ($(myVar).index( mySources )) );
…it returns this:
Index of ../images/homeImages/02.jpg is: -1
This is throwing me. Why would it return -1 for “not found” when it should be retunring 2. It does mat the second slot in the mySources array, no?
You are trying to use index() on an array. It is not intended to be used for anything other than jQuery element objects.
Using $.inArray() would be the better method