Javascript - 更改数量时调整价格

时间:2017-11-22 04:41:02

标签: javascript math

我有一个表单可以将产品添加到购物篮,用户需要选择数量。我正在尝试在修改数量时调整价格。这是我的代码:

  <script>
  function increaseValue() {
    var value = parseInt(document.getElementById('quantity').value, 10);
    value = isNaN(value) ? 0 : value;
    value++;
    document.getElementById('quantity').value = value;
  }

  function decreaseValue() {
    var value = parseInt(document.getElementById('quantity').value, 10);
    value = isNaN(value) ? 0 : value;
    value < 1 ? value = 1 : '';
    value--;
    document.getElementById('quantity').value = value;
  }
  </script>

  <div class="quantity-container">
  <span>1</span> 
 <div class="value-button" id="decrease" onclick="decreaseValue()" value="Decrease Value">-</div> 
<input type="number" id="quantity" name="quantity" value="1" />
<div class="value-button" id="increase" onclick="increaseValue()" value="Increase Value">+</div>
</div>

我需要调整以下方案的价格:

  • 如果使用“增加”按钮增加数量
  • 如果数量减少(但是以0.00美元的价格防止零数量)
  • 如果使用数量文本字段更新数量

问题是价格在数字之间使用html显示,所以我很困惑如何更新价格。我想我将不得不使用RegEx?我不能只硬编码基本价格(本例中为15.49美元),因为价格从不相同(价格来自SQL DB)

<div id="product-price">
$15<sup>.49</sup>
</div>

1 个答案:

答案 0 :(得分:2)

使用ES6&#39; s Template literals (``)。请尝试以下方法:

更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

&#13;
&#13;
function increaseValue() {
  var value = parseInt(document.getElementById('quantity').value, 10);
  value = isNaN(value) ? 0 : value;
  value++;
  document.getElementById('quantity').value = value;
  price = '$'+`<span>${p * value}</span>`;
  document.getElementById('product-price').innerHTML=price;
}

function decreaseValue() {
  var value = parseInt(document.getElementById('quantity').value, 10);
  value = isNaN(value) ? 0 : value;
  value < 1 ? value = 1 : '';
  value--;
  document.getElementById('quantity').value = value;
  price = '$'+`<span>${p * value}</span>`;
  document.getElementById('product-price').innerHTML=price;
}
var p='15.49';
var price = '$'+`<span>${p}</span>`;
document.getElementById('product-price').innerHTML=price;
&#13;
<div id="myDiv">
  <div class="quantity-container">
  <span>1</span> 
  <div class="value-button" id="decrease" onclick="decreaseValue()" value="Decrease Value">-</div> 
  <input type="number" id="quantity" name="quantity" value="1" />
  <div class="value-button" id="increase" onclick="increaseValue()" value="Increase Value">+</div>
</div>

<div id="product-price">

</div>
&#13;
&#13;
&#13;