js制作簡易計(jì)算器
本文實(shí)例為大家分享了js制作簡易計(jì)算器的具體代碼,供大家參考,具體內(nèi)容如下
要制作一個(gè)如圖所示的簡易計(jì)算器,首先要建立一個(gè)表單,制作出如圖所示的樣子。
<table border='1' cellspacing='0' > <tr><th colspan='2'>購物簡易計(jì)算器</th></tr> <tr> <td>第一個(gè)數(shù)</td> <td><input type='text' /></td> </tr> <tr> <td>第二個(gè)數(shù)</td> <td><input type='text' /></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>計(jì)算結(jié)果</td> <td><input type='text' /></td> </tr></table>
onclick使用cal()方法,其實(shí)一開始我是使用add,sub,mul,div四種方法的,后來發(fā)現(xiàn)這四個(gè)方法除了算術(shù)運(yùn)算符不一樣,其他的地方都一樣,所以選擇使用一個(gè)方法,點(diǎn)擊button,傳給方法里的算術(shù)運(yùn)算符不一樣,代碼如下:
<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>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 使用ajax跨域調(diào)用springboot框架的api傳輸文件2. ASP.NET MVC把數(shù)據(jù)庫中枚舉項(xiàng)的數(shù)字轉(zhuǎn)換成文字3. idea右鍵沒有java class選項(xiàng)問題解決方案4. 通過python調(diào)用adb命令對App進(jìn)行性能測試方式5. Python查詢oracle數(shù)據(jù)庫速度慢的解決方案6. python新手學(xué)習(xí)可變和不可變對象7. JS中map和parseInt的用法詳解8. vue中關(guān)于checkbox使用的問題9. python 實(shí)現(xiàn)mysql自動增刪分區(qū)的方法10. Python matplotlib畫圖時(shí)圖例說明(legend)放到圖像外側(cè)詳解
