开发者问题收集

在函数中传递多个 html 元素作为参数[重复]

2021-08-21
472

我想计算某个 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;
}

第一个函数有什么问题?有人可以帮我吗?

3个回答

您以错误的方式使用了 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')
Rahul
2021-08-21

将参数作为数组传递:

totalCalculation(['total-price', 'first-product', 'second-product', 'delivery']);
Snehasish Karmakar
2021-08-21

您的问题与函数中仅声明 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'])
Russ
2021-08-21