嗨,我有一系列图像
["img/wedgallery/1.jpg", "img/wedgallery/2.jpg", "img/wedgallery/3.jpg", "img/wedgallery/4.jpg", "img/wedgallery/5.jpg", "img/wedgallery/6.jpg"]
单击图像时,这将存储为变量“allpics”我想检查它在此数组中的索引。
任何帮助,将不胜感激。
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);
});
您不需要 jQuery,但可以使用 vanilla JavaScript 来完成。使用indexOf()
(MDN 文档):
var index = allpics.indexOf( yourPic );
如果你确实想使用 jQuery,我想你会想使用jQuery.inArray
. 或者,您可以使用 grep。它将在数组中找到满足条件的元素。索引作为回调中的参数传递。
http://api.jquery.com/jQuery.grep/
jQuery.grep( array, function(elementOfArray, indexInArray) [, invert] )
所以
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
}
});
你可以使用jQuery.inArray()
帮助
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);
});