為什么輸出Nan
<!DOCTYPE html>
<html>
?<head>
? <title> 事件</title> ?
? <script type="text/javascript">
??
? ? ? ?
? ? //獲取第一個輸入框的值
? ? var a=document.getElementById("txt1");
? ? a=a-0;
//獲取第二個輸入框的值
? ? var b=document.getElementById("txt2");
? ? b=b-0;
//獲取選擇框的值
? ? var o=document.getElementById("select")
//獲取通過下拉框來選擇的值來改變加減乘除的運算法則
? ? function david(a,b){
? ? ? ? if(o=='+'){
? ? ? ? ? ? var n=a+b;
? ? ? ? }else if(o=='-'){
? ? ? ? ? ? var n=a-b;
? ? ? ? }else if(o=='*'){
? ? ? ? ? ? var n=a*b;
? ? ? ? }else if(o=='/'){
? ? ? ? ? ? var n=a/b;
? ? ? ? }
? ??
? ??
? ? //設置結果輸入框的值?
? ? n=n-0;
? ? document.getElementById('fruit').value=n;
? ? }
? ?
? </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='david()'/> <!--通過 = 按鈕來調用創建的函數,得到結果-->?
? ?<input type='text' id='fruit'/> ??
?</body>
</html>
2016-11-08
var o=document.getElementById("select") 這一行等到的值是object, ?應該寫成.
var o=document.getElementById("select").value 這樣得到的值才是實際的值.
2016-11-09
<html>
?<head>
?
?<script type='text/javascript'>
? function count(){
var a=t1.value; ?
? var b=t2.value;
var sele=se.value;
var n;
switch(sele){
case '+':
n=eval(a)+eval(b);
break;
case '-':
n=eval(a-b);
break;
case '*':
n=eval(a*b);
break;
case '/':
n=eval(a/b);
}
alert(n);
? }?
? </script>
??
?</head>
?
?
?
?<body>
?
? <input type='text' id='t1'/>
? <select id='se'>
? <option>+</option>
? <option>-</option>
? <option>*</option>
? <option>/</option>
? ? </select>
? ? <input type='text' id='t2'/>
? ? <button type='button' onclick='count()'>result</button>
?</body>
</html>
2016-11-09
? var a=parseInt(document.getElementById("t1").value);
? var b=document.getElementById('t2').value;
要放到count()函數內,放在外面就是頁面加載的時候獲取,當然是undefined,放在函數內,則點擊后再獲?。?/p>
b也要加上parseInt(),數字相加才不會出問題
2016-11-08
<html>
?<head>
?
?<script type='text/javascript'>
?//
? var a=parseInt(document.getElementById("t1").value);
? var b=document.getElementById('t2').value;
? function count(a,b){
? //var n=a+b;
? document.write(a);
? document.write(b);
? }
?
? </script>
??
?</head>
?
?
?
?<body>
?
? <input type='text' id='t1'/>
? <select id='se'>
? <option>add</option>
? <option>minus</option>
? <option>mutiply</option>
? <option>divide</option>
? ? </select>
? ? <input type='text' id='t2'/>
? ? <button type='button' onclick='count()'>result</button>
?</body>
</html>
這個里面輸出結果是兩個undefined,所以會出現nan,但是為什么undefined?
2016-11-08
var?a=document.getElemntById('t1').value;
???var?b=document.getElemntById('t2').value;
?改為
var?a= parseInt(document.getElemntById('t1').value;)
???var?b=parseInt(document.getElemntById('t2').value;)
試試?
2016-11-08
這樣也是nan