如何让eval使用本地范围

时间:2015-01-30 23:07:50

标签: javascript jquery

我试图在$ products jquery对象中编写一个循环遍历许多产品元素的函数。

对于每种产品,我想检查其属性数据品牌是否等于用户选择的任何品牌。因此,它遍历已选择的品牌并创建字符串。然后我尝试使用eval()将该字符串转换为if语句的条件表达式。

我这样做的原因是因为会有其他东西的过滤器:产品完成,样式等。还因为过滤器是来自数据库的动态过滤器,它们会随着时间的推移而变化。

//Set Products and selected Bands Jquery Objects
var $products = $('#product-list li');
var $selectedBrands = $('#filters li:checked');
// Loop through the products
$products.each(function(index, element){
    var $this = $(this);
    var hide = true;
    var brandsString = '';
    // loop through the selected brands
    $selectedBrands.each(function(index2, element2){
        // Create a string to use as a conditional
        brandsString += '$(element).attr("data-brand") == $(element2).val()';
        if($selectedBrands.length != index2 + 1){  
            brandsString += ' || ';
        }   
    });
    // This is where things don't work out. I get the error that element2 is undefined
    console.log(eval(brandsString));
    if(eval(brandsString)){
        hide = false;
    }
});

我尝试在内部循环外声明element2,但在所有产品上返回false。

1 个答案:

答案 0 :(得分:2)

请不要使用邪恶的eval

相反,以下内容不会更容易吗?

var b = false; // boolean
$selectedBrands.each(function(index2, element2){
    b = b || $(element).attr("data-brand") == $(element2).val();
});
console.log(b);

但是等等!有Array.prototype.some

var b = [].some.call($selectedBrands, function(element2, index2){
    return $(element).attr("data-brand") == $(element2).val();
});
console.log(b);
相关问题