如何在函数内将字符串转换为整数?

How to convert a string to a integer inside a function?

我想将输入的 id 字符串转换为整数。我正在测试这个 js 函数,尽管 getPrice 正在工作,但 getQty 给我 "undifine" 而不是数字。怎么了?

function getPrice() {
var price = document.getElementById("priceTshirt").innerHTML;
document.getElementById("total-1").innerHTML = price;
}

getPrice();


function getQty() {
var qty = document.getElementById("qty1").innerHTML;
document.getElementById("demolish").innerHTML = qty;
qty = qty.parseInt;
}

getQty();

Qty1 是一个输入元素,它没有 innerHTML。您应该改为获取值:

function getQty() {
    var qty = document.getElementById("qty1").value;
    document.getElementById("demolish").innerHTML = qty;

    return qty;
}

并且您可以使用 getQty 函数返回的数量来设置总价:

function getPrice() {
    var price = parseInt(document.getElementById("priceTshirt").innerHTML);
    document.getElementById("total-1").innerHTML = price * getQty();
}