在函数中将多个 html 元素作为参数传递

pass multiple html element as args in function

我想计算一些 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;
}

第一个功能有什么问题?有人可以帮我吗?

将参数作为数组传递:

totalCalculation(['total-price', 'first-product', 'second-product', 'delivery']);

您的问题与以下事实有关:函数中只声明了 1 个参数,但在调用它时传递了多个参数。

解决方案是将数组作为 1 个参数传递给 totalCalculation 这样做之后,您可以像在函数体中一样迭代它们。

更新代码:


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;
}

// Total Calculation now has 1 argument as an array, that can then be iterated over.
totalCalculation(['total-price', 'first-product', 'second-product', 'delivery']) 

您使用的 arguments 关键字有误。

你不必明确地写出来。

只需使用:

function totalCalculation() {
    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')