計算的結(jié)果是NaN 是怎么回事 請人指教
<!DOCTYPE html>
<html>
?<head>
? <title> 事件</title> ?
? <script type="text/javascript">
? ?function count(){
? ? var txt1=document.getElementById("txt1").value; ??
? ? //獲取第一個輸入框的值
? ? var txt2=document.getElementById("txt2").value;
//獲取第二個輸入框的值
? ? var select1=document.getElementById("select").value;
//獲取選擇框的值
? ? var x=""
? ? switch(select1)
? ? {
? ? ? ? case "+":
? ? ? ? ?x = parseInt("txt1")+parseInt("txt2");
? ? ? ? break;
? ? ? ? case "-":
? ? ? ? ?x = parseInt("txt1")-parseInt("txt2");
? ? ? ? break;
? ? ? ? case "*":
? ? ? ? ? x = parseInt("txt1")*parseInt("txt2");
? ? ? ? break;
? ? ? ? case "/":
? ? ? ? ? x = parseInt("txt1")/parseInt("txt2");
? ? ? ? break;
? ? }
//獲取通過下拉框來選擇的值來改變加減乘除的運算法則
? ? document.getElementById("fruit").value = x;
? ? //設(shè)置結(jié)果輸入框的值?
? ??
? ?}
? </script>?
?</head>?
?<body>
? ?<input type='text' id='txt1' />?
? ?<select id='select'>
<option value='+'>+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
? ?</select>
? ?<input type='text' id='txt2' />?
? ?<input type='button' value=' = ' onclick="count()"/> <!--通過 = 按鈕來調(diào)用創(chuàng)建的函數(shù),得到結(jié)果-->?
? ?<input type='text' id='fruit' /> ??
?</body>
</html>
2016-01-11
因為txt1已經(jīng)是String類型的值了,parseInt(txt1),這樣寫才可以進(jìn)行轉(zhuǎn)換,下面是改好的代碼,你可以看一下
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
</head>
<script type="text/javascript">
function count() {
var txt1 = document.getElementById("txt1").value;
//獲取第一個輸入框的值
var txt2 = document.getElementById("txt2").value;
//獲取第二個輸入框的值
var select1 = document.getElementById("select").value;
//獲取選擇框的值
var x = "";
switch (select1) {
case "+":
x = parseInt(txt1) + parseInt(txt2);
break;
case "-":
x = parseInt(txt1) - parseInt(txt2);
break;
case "*":
x = parseInt(txt1) * parseInt(txt2);
break;
case "/":
x = parseInt(txt1) / parseInt(txt2);
break;
}
//獲取通過下拉框來選擇的值來改變加減乘除的運算法則
document.getElementById("fruit").value = x;
//設(shè)置結(jié)果輸入框的值?
}
</script>
<body>
<input type='text' id='txt1' />
<select id='select'>
<option value='+'>+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type='text' id='txt2' />
<input type='button' value=' = ' onclick="count()" />
<!--通過 = 按鈕來調(diào)用創(chuàng)建的函數(shù),得到結(jié)果-->
<input type='text' id='fruit' />
</body>
</html>
2016-08-22
謝謝,同樣問題解決了。正確:parseInt(參數(shù)),錯誤:parseInt(“參數(shù)”),不用加雙引號“”的緣故
2016-01-11
是因為 txt1本身就是字符串 ?所以不要加""(引號)嗎
2016-01-11
正如樓上說的,你這樣parseInt("txt1")得到的不是數(shù)字,當(dāng)某個運算符不是數(shù)字,那么結(jié)果為 NaN。