javascript - 为什么 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 中获取值。我怎样才能让这个计算器正常工作?
解决方案
简单地这样做
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>
推荐阅读
- r - 将 mutate 与多个函数一起使用
- 3d - 将图像应用于 3d 模型
- ansible - 如何将ansible变量输出分配给嵌套列表中的另一个变量
- php - 导航到另一个页面时显示 404 错误
- python - 如何在 sqlalchemy 中删除表并重新创建它
- laravel - 如何在 Laravel+Vue 中使用枢轴额外字段进行多重附加
- git - 在git中设置上游分支:分支不存在
- selenium-webdriver - Selenium:如何与 Ckeditor 文件浏览器交互
- .net - 通过 vb.NET PSCommand 执行 Powershell 命令 Clear-Disk
- npm - 命令“npm run dev”失败 NuxtJS