要制作一個如圖所示的簡易計算器,首先要建立一個表單,制作出如圖所示的樣子,
<table border="1" cellspacing="0" >
<tr><th colspan="2">購物簡易計算器</th></tr>
<tr>
<td>第一個數</td>
<td><input type="text" id="inputId1" /></td>
</tr>
<tr>
<td>第二個數</td>
<td><input type="text" id="inputId2" /></td>
</tr>
<tr>
<td><button type="button" onclick="cal('+')" >+</button></td>
<td><button type="button" onclick="cal('-')" >-</button>
<button type="button" onclick="cal('*')" >*</button>
<button type="button" onclick="cal('/')" >/</button></td>
</tr>
<tr>
<td>計算結果</td>
<td><input type="text" id="resultId"/></td>
</tr>
</table>
onclick使用cal()方法,其實一開始我是使用add,sub,mul,div四種方法的,
后來發現這四個方法除了算術運算子不一樣,其他的地方都一樣,所以選擇使用
一個方法,點擊button,傳給方法里的算術運算子不一樣,代碼如下:
<script type="text/javascript">
function cal(type){
var num1 = document.getElementById('inputId1');
var num2 = document.getElementById('inputId2');
var result;
switch(type){
case '+':
result = parseInt(num1.value) + parseInt(num2.value);
break;
case '-':
result = parseInt(num1.value) - parseInt(num2.value);
break;
case '*':
result = parseInt(num1.value) * parseInt(num2.value);
break;
case '/':
result = parseInt(num1.value) / parseInt(num2.value);
break;
}
var resultObj = document.getElementById('resultId');
resultObj.value = result;
}
</script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/293196.html
標籤:其他
上一篇:javascript簡單計算器
下一篇:淺學JavaScript05
