简体   繁体   中英

How to have eval use the local scope

I'm trying to writ a function that will loop through a number of product elements, inside a $products jquery object.

For each product, I want to check if its attribute data brand equals any of the brands the user has selected. So, it loops through the the brands that have been selected and creates a string. Then I'm trying to use eval() to convert that string into a conditional expression for an if statement.

The reason I'm doing it this way is because there are going to be filters for other stuff: Product finishes, styles, etc. And also because the filters are dynamic coming from the database and they will change over time.

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

I tried declaring element2 outside the inside loop, but that returned false on all the products.

Please don't use evil eval .

Instead, wouldn't the following be easier?

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

But wait! There is Array.prototype.some :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM