我有一个图片库,可以按专辑排序。
我有一个像:
这样的数组var images_gallery = [
{
image_src: "images/xmas-1.jpg",
album: "xmas"
},
{
image_src: "images/xmas-2.jpg",
album: "xmas"
},
{
image_src: "images/xmas-3.jpg",
album: "xmas"
},
{
image_src: "images/xmas-4.jpg",
album: "summer"
}
]
我的html中也有一个选择:
<select name="album">
<option selected="selected" id="all">All</option>
<option id="xmas">Xmas Party</option>
<option id="summer">Summer Party</option>
</select>
然后在我的js文件中:
$("select[name='album']").change(function() {
var thisAlbum = $(this).children(":selected").attr("id");
});
我的问题是,如何按照与我的选择选项ID匹配的相册过滤我的数组(然后显示它们,我有一个函数(showImages))。
编辑:
使用下面的答案我已经到了这里:
$("select[name='album']").change(function() {
var thisAlbum = $(this).children(":selected").attr("id");
var filteredArray = images_gallery.filter(function(x) {
return x.album == thisAlbum;
});
$('#librarian-page-container-gallery').html(' ');
Shadowbox.setup("a.gallery", {
gallery: "gallery",
});
filteredArray.showImages2();
});
我不确定如何将我的函数应用于新过滤的数组?
我的功能如下:
function showImages2(){
$.each(images_gallery,function(i,image_gallery){
// stuff in here
});
}
感谢您的帮助到目前为止!
答案 0 :(得分:1)
您可以使用filter
过滤数组:
var filteredArray = images_array.filter(function(x) {
return x.album == thisAlbum;
});
Here's a shim获取旧版浏览器的支持。
答案 1 :(得分:0)
使用David的答案过滤结果。
$("select[name='album']").change(function() {
var thisAlbum = $(this).children(":selected").attr("id");
var result = images_gallery.filter(function(x) {
return x.album == thisAlbum;
});
//Clear images
$('#images').html(' ');
//Show images in new result array
for(img in result){
$('#images').append('<img src="' + result[img].image_src + '" />');
}
});
答案 2 :(得分:0)
如果你想使用jQuery,你可以使用.grep
:
var filterArray = $.grep(images_gallery, function(obj) {
return obj.album === thisAlbum;
});
对thisAlbum进行了更改,如果它的'all'然后获取数组中的所有对象:http://jsfiddle.net/4tEz4/
var filterArray = $.grep(images_gallery, function(obj) {
return thisAlbum === 'all' || obj.album === thisAlbum;
});
或只是:
var filterArray = thisAlbum === 'all' ? images_gallery : $.grep(images_gallery, function(obj) {
return obj.album === thisAlbum;
});