寶貝er瑩
2015-12-16 14:22:23
<!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 select=document.getElementById("select").value; //獲取通過下拉框來選擇的值來改變加減乘除的運算法則? ? var result="";? ? switch(select)? ? ? ? case "+":? ? ? ? ? ? result=parseInt(txt1)+parseInt(txt2);? ? ? ? ? ? break;? ? ? ? case "-":? ? ? ? ? ? result=parseInt(txt1)-parseInt(txt2);? ? ? ? ? ? break;? ? ? ? case "*":? ? ? ? ? ? result=parseInt(txt1)*parseInt(txt2);? ? ? ? ? ? break;? ? ? ? default:? ? ? ? ? ? result=parseInt(txt1)/parseInt(txt2);? ? //設(shè)置結(jié)果輸入框的值?? ? document.getElementById("fruit").value = result;? ?}? </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>
4 回答
已采納

Caballarii
TA貢獻1123條經(jīng)驗 獲得超629個贊
switch(select){
? ? ? ? case "+":
? ? ? ? ? ? result=parseInt(txt1)+parseInt(txt2);
? ? ? ? ? ? break;
? ? ? ? case "-":
? ? ? ? ? ? result=parseInt(txt1)-parseInt(txt2);
? ? ? ? ? ? break;
? ? ? ? case "*":
? ? ? ? ? ? result=parseInt(txt1)*parseInt(txt2);
? ? ? ? ? ? break;
? ? ? ? default:
? ? ? ? ? ? result=parseInt(txt1)/parseInt(txt2);
}
switch語句塊需要用{}括起來

Perona
TA貢獻355條經(jīng)驗 獲得超403個贊
一般來說只有一條語句可以省略花括號,但是多條語句最好不要省略花括號。
這里的switch里有多條語句,不能省略花括號,會出現(xiàn)編譯錯誤。加上即可。
添加回答
舉報
0/150
提交
取消