Reputation: 17467
hi I have an array of images
["img/wedgallery/1.jpg", "img/wedgallery/2.jpg", "img/wedgallery/3.jpg", "img/wedgallery/4.jpg", "img/wedgallery/5.jpg", "img/wedgallery/6.jpg"]
this is stored as a variable 'allpics' when an image is clicked I want to check for its index within this array.
Any help would be appreciated.
Upvotes: 1
Views: 482
Reputation: 921
var allpics = ["img/wedgallery/1.jpg", "img/wedgallery/2.jpg", "img/wedgallery/3.jpg", "img/wedgallery/4.jpg", "img/wedgallery/5.jpg", "img/wedgallery/6.jpg"];
$('img').click(function(){
var src = $(this).attr('src');
var index = $.inArray(src, allpics);
});
Upvotes: 2
Reputation: 6749
If you do want to use jQuery, I'd imagine you would want to use jQuery.inArray
. Alternately, you can use grep. It will find an element in array that satisfies a condition. the index is passed as a parameter in the callback.
http://api.jquery.com/jQuery.grep/
jQuery.grep( array, function(elementOfArray, indexInArray) [, invert] )
so
var img = //clicked elements src attrib
// s is the element selected from the array
var s = $.grep(allImages, function(elem, i) {
if (img == elem.attr('src'))
{
//i is the index in allImages
}
});
Upvotes: 0
Reputation: 206151
You can use jQuery.inArray()
help
var images = ["img/wedgallery/1.jpg", "img/wedgallery/2.jpg", "img/wedgallery/3.jpg", "img/wedgallery/4.jpg", "img/wedgallery/5.jpg", "img/wedgallery/6.jpg"];
$('img').click(function(){
var src = $(this).attr('src');
var myArrIndexIs = $.inArray(src, images);
alert(myArrIndexIs);
});
Upvotes: 0