2 回答

TA貢獻(xiàn)1847條經(jīng)驗(yàn) 獲得超11個(gè)贊
試試這個(gè):
function calcTotal() {
// remove $ sign and parse Float price
var price = parseFloat(document.getElementById("price").value.substr(1));
// parse float quantity
var quantity = parseFloat(document.getElementById("quantity").value);
var total = price * quantity;
//pass calculated value to input with id total
document.getElementById("total").value = "$" + total;
}
<input id="price" type="text" readonly value="$18.95">
<input id="quantity" type="text" value="1" onchange="calcTotal()">
<input id="total" type="text" readonly value="">

TA貢獻(xiàn)1883條經(jīng)驗(yàn) 獲得超3個(gè)贊
任何涉及字符串的操作都會(huì)返回 ,但是您應(yīng)該強(qiáng)制輸入值NaNNumber
function calcTotal() {
var price = document.getElementById("price").value;
var quantity = document.getElementById("quantity").value;
var total =Number(price) * Number(quantity);
console.log(total);
}
使用數(shù)字與解析浮動(dòng)
因此,只要您有標(biāo)準(zhǔn)的數(shù)字輸入,就沒(méi)有區(qū)別。但是,如果您的輸入以數(shù)字開(kāi)頭,然后包含其他字符,parseFloat 會(huì)將數(shù)字從字符串中截?cái)啵鴶?shù)字則給出 NaN(不是數(shù)字):
parseFloat('1x'); // => 1
Number('1x'); // => NaN
添加回答
舉報(bào)