我已经建立了一个小的“折扣”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
}
});
我当然会将这个添加到插件中,而不是我在上面的例子中调用它,但我不知道如何以流畅和友好的方式实现这样的事情。
答案 0 :(得分:1)
我会添加一个像这样的配置对象:
$('.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 ....
}