我這個代碼,為什么加法運算不是2數相加?找不到哪里寫錯了?
<!DOCTYPE html>
<html>
?<head>
? <title> 事件</title> ?
? <script type="text/javascript">
? ?function count(){
? ? var p1=document.getElementById("txt1").value;
? ? //獲取第一個輸入框的值
? ? var p2=document.getElementById("txt2").value;
? ? //獲取第二個輸入框的值
var p="";
? ? //獲取選擇框的值
? ? var px=document.getElementById("select").value;
//獲取通過下拉框來選擇的值來改變加減乘除的運算法則
? ? //設置結果輸入框的值?
? ?switch(px)
? ?{
? ? ? ?case "+":
? ? ? ? ? ?p = p1 +p2;
? ? ? ? ? ?break;
? ? ? ?case "-":
? ? ? ? ? ?p = p1 -p2;
? ? ? ? ? ? break;
? ? ? ?case "*":
? ? ? ? ? ?p = p1*p2;
? ? ? ? ? ? break;
? ? ? ?case "/":
? ? ? ? ? ?p = p1/p2;
? ? ? ? ? ? break;
? ?}
? document.getElementById("fruit").value=p;
? ?
? ?}
? </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=' = ' /> <!--通過 = 按鈕來調用創建的函數,得到結果-->?
? ?<input type='text' id='fruit' onclick="count()" /> ??
?</body>
</html>
2016-02-01
你的p1和p2接收到的是String類型的值 你用alert(typeof(p1))試一下就知道了?? 要用parseInt轉型
2016-02-02
我還有點不明白,為什么就是第一個case是字符串,其他的case就是number類型呢?
在case“-”后面加了alert(typeof(p)); 是彈出number類型的?
但是為什么會這樣?
2016-02-02
我還有點不明白,為什么就是第一個case是字符串,其他的case就是number類型呢?
在case“-”后面加了alert(typeof(p)); 是彈出number類型的?
但是為什么會這樣?