获得输出作为' Nan'

时间:2017-07-10 04:28:40

标签: javascript

当我在一个事件上调用此函数时,它会给我一个输出作为' Nan'。那是为什么?

function fillValue(id){
    var qty = Number(document.getElementById('quantity' + id));
    var price = Number(document.getElementById('price' + id));

    var total = Number(qty * price);
    document.getElementById('value' + id).value = total;

}

3 个答案:

答案 0 :(得分:0)

Nan是"不是数字"

document.getElementById返回HTML元素。你不能将html元素转换为数字。

document.getElementById('quantity' + id)document.getElementById('price' + id这些是Nan。您正在尝试多个NaN,因此您获得了NaN

如果它是input,您可以使用document.getElementById('quantity' + id).value

获取其价值

您的代码将如下所示

function fillValue(id){
    const qty = Number(document.getElementById('quantity' + id).value);
    const price = Number(document.getElementById('price' + id).value);

    const total = qty * price;
    document.getElementById('value' + id).value = total;
}

答案 1 :(得分:0)

您为qty和price变量错过了.value

    function fillValue(id){
    var qty = Number(document.getElementById('quantity' + id).value);
    var price = Number(document.getElementById('price' + id).value);

    var total = Number(qty * price);
    document.getElementById('value' + id).value = total;

}

答案 2 :(得分:0)

尝试将元素的内容转换为整数。

function fillValue(id){
    var qty = document.getElementById('quantity' + id);
    var price = document.getElementById('price' + id);

    //parse to number
    qty = parseInt(qty);
    price = parseInt(price);

    var total = (qty * price);
    document.getElementById('value' + id).value = total;

}
相关问题