gpt4 book ai didi

Javascript - 更改数量时调整价格

转载 作者:行者123 更新时间:2023-12-01 02:43:05 25 4
gpt4 key购买 nike

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

  <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 显示的,所以我很困惑如何更新价格。我想我必须使用正则表达式?我不能只是硬编码基本价格(本例中为 15.49 美元),因为价格永远不会相同(价格来自 SQL DB)

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

最佳答案

使用ES6模板文字(``)。请尝试以下操作:

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

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;
<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>

关于Javascript - 更改数量时调整价格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47426929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com