標籤:
編程練習
使用JS完成一個簡單的計算機功能。實現2個輸入框中輸入整數後,點擊第三個輸入框能給出2個整數的加減乘除。
提示:擷取元素的值設定和擷取方法為:例:賦值:document.getElementById(“id”).value = 1; 取值:var = document.getElementById(“id”).value;
任務
第一步: 建立構建運算函數count()。
第二步: 擷取兩個輸入框中的值和擷取選擇框的值。
提示:document.getElementById( id名 ).value 擷取或設定 id名的值。
第三步: 擷取通過下拉框來選擇的值來改變加減乘除的運演算法則。
提示:使用switch判斷運演算法則。
第四步: 通過 = 按鈕來調用建立的函數,得到結果。
注意: 使用parseInt()函數可解析一個字串,並返回一個整數。
<!DOCTYPE html>
<html>
<head>
<title> 事件</title>
<script type="text/javascript">
function count(){
var s;
//擷取第一個輸入框的值
var one=document.getElementById("txt1").value;
//擷取第二個輸入框的值
var two=document.getElementById("txt2").value;
//擷取選擇框的值
var sel=document.getElementById("select").value;
//擷取通過下拉框來選擇的值來改變加減乘除的運演算法則
switch(sel){
case "+":s=parseInt(one)+parseInt(two);
break;
case "-":s=parseInt(one)-parseInt(two);
break;
case "*":s=parseInt(one)*parseInt(two);
break;
case "/":s=parseInt(one)/parseInt(two);
}
//設定結果輸入框的值
document.getElementById("fruit").value=s;
}
</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()" /> <!--通過 = 按鈕來調用建立的函數,得到結果-->
<input type=‘text‘ id=‘fruit‘ />
</body>
</html>
JavaScript 事件 編程練習