0

我有一个图像库,我希望能够按专辑排序。

我有一个像这样的数组:

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
    });
}

感谢您一直以来的帮助!

4

3 回答 3

1

您可以使用以下方法过滤您的数组filter

var filteredArray = images_array.filter(function(x) {
   return x.album == thisAlbum;
});

这是旧浏览器支持的垫片。

于 2013-02-01T12:52:15.937 回答
0

Using David's answer to filter the results.

$("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 + '" />');
    }
});

http://jsfiddle.net/vyaTC/1/

于 2013-02-01T12:57:11.857 回答
0

if you want to use jQuery you could use .grep:

var filterArray = $.grep(images_gallery, function(obj) {
    return obj.album === thisAlbum;
});

did a change on thisAlbum if its 'all' then get all objects in the array: http://jsfiddle.net/4tEz4/

var filterArray = $.grep(images_gallery, function(obj) {
    return thisAlbum === 'all' || obj.album === thisAlbum;
});

or just:

var filterArray = thisAlbum === 'all' ? images_gallery : $.grep(images_gallery, function(obj) {
    return obj.album === thisAlbum;
});
于 2013-02-01T12:57:22.093 回答