从span标签中获取值并从中扣除%(JavaScript)

Get value from span tag and deduct % from it (JavaScript)

本文关键字:JavaScript span 标签 获取      更新时间:2023-09-26

在产品页面上,价格显示在两个 span 标签内:

<div class="price-container">
    <span class="price-regular">
        <span class="price">$10.00</span>
    </span>
</div>

我想做的是从正常价格中扣除 15%,并在其下方显示扣除的金额。由于价格字段是动态的,并且值还包含$符号,我该如何完成此操作?我需要使用 JavaScript 进行计算,但我仍在学习它。

您可以通过获取当前价格,然后进行数学运算进行调整来显示调整后的价格。 最后将折扣价添加到 HTML DOM。

.HTML

<span class="price">$10.00</span>

JavaScript

//build an array with all the prices
var spans = document.getElementsByClassName('price');
//set the discount
var discount = .15;
//loop over all the prices
for(var i = 0; i < spans.length; i++) {
  //get the price
    var price = spans[i].innerHTML;
  //remove the dollar sign
  price = price.replace('$','');
  //convert the price to a float
  price = parseFloat(price);
  //apply the discount, and use toFixed(2) for ensure we keep 2 decimal places
  var discountedPrice = (price * (1-discount)).toFixed(2);
  //update the HTML by adding the discounted price below the original
  spans[i].innerHTML = '<s>'+spans[i].innerHTML + '</s><br />$' + discountedPrice;
}

你可以看到它在这个JS小提琴中工作:https://jsfiddle.net/x4zjkv68/2/

希望对您有所帮助!