【问题标题】:jquery find image in arrayjquery在数组中查找图像
【发布时间】:2012-08-15 20:50:38
【问题描述】:
嗨,我有一组图像
["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' 我想检查它在这个数组中的索引。
任何帮助将不胜感激。
【问题讨论】:
标签:
jquery
arrays
indexing
find
【解决方案1】:
您不需要 jQuery,但可以使用 vanilla JavaScript 来完成。使用indexOf() (MDN docu):
var index = allpics.indexOf( yourPic );
【解决方案2】:
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);
});
【解决方案3】:
您可以使用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);
});
【解决方案4】:
如果你确实想使用 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
}
});