javascript - html 内容中的数字不断增加

标签 javascript html

我想增加 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 元素中已有的内容中,您可以执行以下步骤:

  1. 首先删除不属于数字的字符(例如美元符号)来解析当前内容;
  2. 将其转换为数字,并让空字符串为0
  3. 添加价格
  4. 再次将其格式化为货币金额
  5. 将其放入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/

相关文章:

javascript - 菜单卡住,无法点击

html - Bootstrap - 相对于父 col 的 col 大小

javascript - scrollTop() 并不总是有效

javascript - Three.js 的输入标签不起作用

javascript - 为什么 "i"不等于 "i̇"?

javascript - 将默认值放入 &lt;input type=file....>

javascript - AJAX:向表中添加新行或使用 AJAX 删除

html - 更流畅的背景图像动画(防止闪烁)

javascript - 如何从 sqlalchemy jsonify 对象?

javascript - 您应该如何使用 jQuery .on 将上下文传递给命名函数?