【发布时间】:2021-10-22 11:58:42
【问题描述】:
我想计算一些html元素的innerText。
为此,我编写了一个将“arguments”关键字作为参数的函数。这样我就可以传递尽可能多的元素。
函数体如下:
function totalCalculation(arguments) {
let total = 0;
for (i = 0; i < arguments.length; i++) {
// getting all the required fields to be calculated from the arguments
const fieldAmount = parseInt(document.getElementById(arguments[i]).innerText);
total += fieldAmount;
}
document.getElementById('total-price').innerText = total;
document.getElementById('grand-total-price').innerText = total;
}
totalCalculation('total-price', 'first-product', 'second-product', 'delivery')
但该功能给我错误提示:Uncaught TypeError: Cannot read property 'innerText' of null
但是,如果我像下面这样编写函数,它就可以工作:
function totalCalculation() {
const totalPrice = parseInt(document.getElementById('total-price').innerText);
const firstProductPrice = parseInt(document.getElementById('first-
product').innerText);
const secondProductPrice = parseInt(document.getElementById('second-
product').innerText);
const deliveryCharge = parseInt(document.getElementById('delivery').innerText);
const total = totalPrice + firstProductPrice + secondProductPrice +
deliveryCharge
document.getElementById('total-price').innerText = total;
document.getElementById('grand-total-price').innerText = total;
}
第一个函数有什么问题?有人可以帮帮我吗?
【问题讨论】:
-
当您使用 es6 语法时,处理变量参数的推荐方法是使用
function totalCalculation(...args),其中args将是您的参数数组,而不是使用arguments对象
标签: javascript html function dom arguments