我想增加 HTML 内容的数量并将其格式化为货币,例如:“$ 12.50”。
在我的例子中,有一个价格和产品数组,代码必须访问相应的数组,以便选择产品、查找其价格,如果 HTML 中没有值,则将该值发送到HTML标签,如果html标签中有Some值,则增加到现有值。
示例:
function(product, amount){
// search the index
var index = arrayProduct.indexOf(product);
// points the element by index
var price = arrayPrices[index];
// If the tag is empty, it sends, if there is any value in the tag, it increases
document.getElementById("idPrice").innerHTML = price;
}
最佳答案
假设您想要将价格添加到 idPrice 元素中已有的内容中,您可以执行以下步骤:
- 首先删除不属于数字的字符(例如美元符号)来解析当前内容;
- 将其转换为数字,并让空字符串为0
- 添加价格
- 再次将其格式化为货币金额
- 将其放入idPrice
这是执行此操作的代码:
var elem = document.getElementById("idPrice");
elem.textContent = '$ ' + (+elem.textContent.replace(/[^\d.]/, '') + price).toFixed(2)
一般来说,对于非 HTML 内容,最好使用 textContent
而不是 innerHTML
。
此外,如果您将存储在 idPrice 中的价格保留在数字变量中会更好,这样您就不必在每次添加时都对格式化价格进行解码。
这是一个允许选择产品的简单片段。单击“添加”按钮时,将调用该函数:
var arrayProduct = ['coffee', 'pizza', 'apple pie', 'wine'];
var arrayPrices = [1.10, 5.13, 3.90, 2.99];
function updateTotal(product){
// Search the index
var index = arrayProduct.indexOf(product);
if (index == -1) return; // exit when product not found
// There is a match. Get the corresponding price
var price = arrayPrices[index];
// Convert the tag content to number, add the price and update the
// tag content accordingly
var el = document.getElementById("idPrice");
el.textContent = '$ ' + (+el.textContent.replace(/[^\d.]/, '') + price).toFixed(2);
}
document.querySelector('button').onclick = function () {
updateTotal(document.querySelector('select').value);
};
<select>
<option></option>
<option value="coffee">coffee ($ 1.10)</option>
<option value="pizza">pizza ($5.13)</option>
<option value="apple pie">apple pie ($ 3.90)</option>
<option value="wine">wine ($ 2.99)</option>
</select>
<button>Add</button><br>
Total: <span id="idPrice"></span>
关于javascript - html 内容中的数字不断增加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41645214/