根据 if / else 语句修改设置“选项”值

Modify settings "option" value based on if / else statements

本文关键字:选项 设置 修改 if else 语句 根据      更新时间:2023-09-26

我构建了一个小的"折扣"jquery插件,可以改变产品的价格。该插件根据选项中设置的折扣百分比值修改所有价格,并且还排除了某些ID,该ID也可以在选项中设置。

这是一个工作小提琴:https://jsfiddle.net/panoply/y2qw3ncu/3/

我现在需要根据某些产品ID添加其他折扣值,但我不确定如何继续。为了更好地解释我想要实现的目标(我知道这是不正确的,但举个例子):

$('.price').TTprices({
    if (products: ['a1','a2']) 
    {
        discount: 10
    } 
    else if (products: ['a3'])
    {
        discount: 20
    }  
    else {
        discount: 50
    }  
});

我当然会将其添加到插件中,而不是我在上面示例中调用它的地方,但是我不知道如何以流畅友好的方式实现这样的事情。

我会添加一个这样的配置对象:

$('.price').TTprices({
    discount: 50,
    products: [{
        id: 'a1',
        extraDiscount: 10
    }, {
        id: 'a2'
    }, {
        id: 'a3',
        extraDiscount: 30
    }],
});

然后,在您的插件中,迭代这些折扣:

return this.each(function() {
    var $this = $(this);
    var $value = $this.contents()[0].textContent;
    var $price = parseFloat($value);
    var $discount = settings.discount;
    var $total = $price - ($price * $discount);
    var $productID = $this.data('product-id');
    var $products = (settings.products);
    var $saleTag = $this.find("span[data-badge='priceline']"); // Sale Tag
    $this.html(function() {
        for (var i = 0; i < $products.length; i++) {
            var item = $products[i];
            if (item.id == $productID) {
                if ($value >= (settings.threshold)) {
                    var extraDiscount = item.extraDiscount ? item.extraDiscount : 0;
                    $discount = ($discount + extraDiscount) / 100;
                    $total = $price - ($price * $discount);
                    $saleTag.html(($discount * 100) + '% OFF');
                    return $this.html().replace($value, $total.toFixed(2) + " ");
                }
            }
        }
        $saleTag.empty();
        return $this.html();
    });
});

工作小提琴:https://jsfiddle.net/skaparate/gc13vnqb/

更新

要修复您的代码,只需更改内部for循环迭代index name

for (var i = 0; i < $products.length; i++) {
    var item = $products[i];
    var itemIds = $products[i].id;
    // The $productID need to be an array (My issue is here)
    // Here you cannot use var i, since it's defined in the parent loop
    var inArray = false;
    for (var j = 0; j < itemIds.length; j++) {
        if (itemIds[j] == $productID) {
            inArray = true;
            break;
        }
    }
    // Other code ....
}