每个jQuery,我需要在这里创建一个闭包吗?

时间:2013-08-28 05:19:11

标签: jquery closures underscore.js

我有以下(缩短了数组)使用jQuery和Underscore:

var all_methods = ['locations', 'items', 'by-cocktails'];
var to_methods = [];
$.each(all_methods, (function (key, val) {
    if ($('.lm-search-options[data-action=' + val + ']').hasClass('del')) {
        console.log('to remove: ' + val); // <- only the last piece is moved out despite multiple pieces being here
        to_methods = _.without(all_methods, val);
    }
}));

我看到的行为是,只删除了最后一个选定的dom元素(是的,我知道这不会赢得任何软件设计奖项)。例如,如果要删除“位置”和“商品”,则只删除“商品”。我看到的行为是因为这里需要一个新的闭包吗?

1 个答案:

答案 0 :(得分:1)

尝试

var $opts = $('.lm-search-options');
var to_methods = _.filter(all_methods, function(val){
    return !$opts.filter('[data-action=' + val + ']').hasClass('del')
})