2013-12-11 43 views
0

我想按多种属性(如流派或格式)对一组影片进行排序。这个想法是,用户用复选框元素选择他想要在屏幕上显示的电影类型。我的问题是,它怎么能插入几个属性,比如像数组一样插入几个名字来过滤它们?用于过滤元素的属性数组

<div id="filters" class="filters"> 
    <strong>Format:&nbsp</strong> 
    <input type="checkbox" name="format" value="Standard">Standard &nbsp&nbsp 
    <input type="checkbox" name="format" value="3D">3D &nbsp&nbsp 
    <input type="checkbox" name="format" value="Imax">Imax <br> 

    <strong>Genre:&nbsp</strong> 
    <input type="checkbox" name="genre" value="comedy">Comedy &nbsp&nbsp 
    <input type="checkbox" name="genre" value="drama">drama &nbsp&nbsp 
    <input type="checkbox" name="genre" value="sciencefiction">Science fiction &nbsp&nbsp 
    <input type="checkbox" name="genre" value="horror">Horror <br> 

</div> 
+1

不能帮助你,如果我们不知道你是如何规划它的工作。你如何向我们展示一些你试图用来获得过滤效果的代码 - 即这个属性数组来过滤以及如何测试每个元素 – megawac

回答

0

假设电影都用数组表示:

var movies = [ 
    { 
    title: 'Avatar', 
    format: '3D', 
    genre: 'sciencefiction' 
    }, 
    { 
    title: 'Saw', 
    format: 'Standard', 
    genre: 'horror' 
    } 
]; 

你需要过滤基于被检查什么的复选框数组。你可以在事件监听器做到这一点:

// Some code skipped for brewity 

$controls.on('change', function() { 
    var formats = $formats.filter(':checked').map(getValue).get(); 
    var genres = $genres.filter(':checked').map(getValue).get(); 

    var filtered = movies.filter(function (e) { 
     var formatMatch = formats.length === 0 || formats.indexOf(e.format) > -1; 
     var genreMatch = genres.length === 0 || genres.indexOf(e.genre) > -1; 

     return formatMatch && genreMatch; 
    }); 

    render($output, filtered); 
}); 

完整的示例:http://jsfiddle.net/V4aW2/