Javascript 将输出获取为';楠';

Javascript 将输出获取为';楠';,javascript,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

当我对一个事件调用这个函数时,它会给我一个输出“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;

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

您缺少数量和价格变量的
.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;

}

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

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;

}

请提供html。您正在尝试将html元素转换为数字,而不是它们的内容或值(在输入字段中)。缺少链接到
文档的
.value
。getElementById('quantity'+id)
文档.getElementById('quantity'+id')
返回一个
HTMLElement
如果您试图从HTML元素创建一个数字,您可能应该使用
number(document.getElementById('quantity'+id).textContent)
number(document.getElementById('quantity'+id).value)