【发布时间】:2021-04-01 14:41:58
【问题描述】:
您好,我正在尝试计算使用 Vanilla JS 销售的产品的折扣百分比。因此,如果销售价格存在“.product-price__discount”,那么我想计算出该产品的折扣百分比。
到目前为止,我能够计算出第一个产品的折扣。在第二个产品上,它似乎打印了与第一个产品相同的折扣,最后一个产品没有销售,因此忽略这一点是正确的。我也知道 .length 有错误,但不知道如何解决。
var pattern = /[^0-9\.]/g;
var price = document.querySelectorAll('.product-slab__price');
price.forEach(function(el){
if(!el.querySelector('.product-price__discount').length) {
var wasPrice = parseFloat(document.querySelector('.product-price__was').textContent.replace(pattern, "")) / 100;
var newPrice = parseFloat(document.querySelector('.product-price__discount').textContent.replace(pattern, "")) / 100;
var subtractPrice = (wasPrice - newPrice);
var dividePrice = (subtractPrice / wasPrice);
var multiplyPrice = (dividePrice * 100);
el.querySelector('.discountPercentage').innerHTML = multiplyPrice.toFixed(0) + "%";
}
});
.product-price__was {
text-decoration: line-through;
}
.product-price__discount {
color: red;
}
<div class="product-slab__price">
<div class="product-price__primary">
<span class="product-price__was">Was €10,00</span>
<span class="product-price__discount">Now €8,00</span>
<span class="discountPercentage" > </span>
</div>
</div>
<div class="product-slab__price">
<div class="product-price__primary">
<span class="product-price__was">€15,00</span>
<span class="product-price__discount">€10,00</span>
<span class="discountPercentage" > </span>
</div>
</div>
<div class="product-slab__price">
<div class="product-price__primary">
<span class="product-price__value">€15,90</span>
<span class="discountPercentage" > </span>
</div>
</div>
【问题讨论】:
标签: javascript foreach percentage discount