javascript - 如何让 eval 使用本地范围

标签 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。

最佳答案

请不要使用邪恶的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);

关于javascript - 如何让 eval 使用本地范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28246112/

相关文章:

javascript - jquery.dataTables : how to change totally contained data/aaData?

javascript - 使用 html 的 bootstrap 3 工具提示不起作用

javascript - 访问 JSON 对象中的数组元素

javascript - jQuery:将 $this 与其他参数一起传递给函数

javascript - JQuery UI 对话框正确显示

javascript - Jquery 加载 https url

jquery访问表中的兄弟TD

javascript - 悬停时识别 Javascript 上的单词

javascript - 将多个 HTML 输入更改为不同的值

jquery - YUI 有像 jQuery 那样的选择器吗?