首页 > 解决方案 > 为什么 checkout-price 的值读取为 null?

问题描述

我试图从几个元素中获取一串文本并删除符号以将其转换为数字,然后组合数字以获得总值,然后我更新总元素。我收到一条错误消息,提示“无法读取属性”长度“为空。”

这是我正在尝试制作的代码,但我不确定我是否走在正确的轨道上。

let price_calc = document.querySelectorAll("#checkout-price");
let total = ""
for (i = 0; i <= price_calc.length; i++){
    total += (Number(price_calc[i].textContent.replace(/[^\d|.]/g, "")))
}
let costEl = document.getElementById("total-cost")
costEl.textContent = `$${total}` 

和 HTML:

<div class='price' id="checkout-price">$523.61 (GST Inc)</div>
<div class='price' id="checkout-price">$137.23 (GST Inc)</div>
<div class='price' id="checkout-price">$274.20 (GST Inc)</div>
<div class='price_sum'id="total-cost">$00.00</div>

我可能有错误的方法从 div 中获取值。我怎样才能让这个计算器正常工作?

标签: javascripthtmlcss

解决方案


简单地这样做

const price_calc = document.querySelectorAll(".price")
  ,   costEl     = document.getElementById("total-cost")
  ;
let total = [...price_calc]
              .reduce((tot,el)=>
                  {
                  tot += Number(el.textContent.replace(/[^\d|.]/g, ""))
                  return tot
                  }
                  ,0)
 
costEl.textContent = `$ ${total}` 
<div class="price">$ 523.61 (GST Inc)</div>
<div class="price">$ 137.23 (GST Inc)</div>
<div class="price">$ 274.20 (GST Inc)</div>
<div class="price_sum" id="total-cost">$ 00.00</div>


推荐阅读