【问题标题】:Increasing numbers in html content增加 html 内容中的数字
【发布时间】:2017-01-13 23:53:37
【问题描述】:

我想增加 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;
}

【问题讨论】:

  • 所以可能是一个if 语句首先从标签中获取值(或缺少值),然后在现有的最后一行之前将其添加到price
  • 递增,比如用一美元?还是一分钱?还是添加的金额?
  • 就像一美元和美分一样:U$ 1.50 @trincot
  • 我认为您的意思是 add 而不是 increment。看我的回答。

标签: javascript html


【解决方案1】:

假设您要将价格添加到 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 中的价格保存在一个数字变量中,这样您就不必在每次添加时都解码格式化的价格。

这是一个简单的 sn-p,允许选择产品。单击“添加”按钮时,将调用该函数:

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>

【讨论】:

  • 结果为 NaN
  • html元素为:
    R$ 0.00
  • 我添加了一个演示 sn-p。如您所见,它有效。您的代码或 HTML 中可能还有其他问题。
猜你喜欢
  • 1970-01-01
  • 2020-03-30
  • 2019-05-04
  • 2013-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-07
  • 1970-01-01
相关资源
最近更新 更多