JavaScript实现简易计算器
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript"> function fn(x){ //得到文本框 和 div的元素对象 var i1 = document.getElementById("i1"); var i2 = document.getElementById("i2"); var d1 = document.getElementById("d1"); //switch-case 一般的用它来做值匹配的 switch(x){ case 1://加 d1.innerText = parseFloat(i1.value)+parseFloat(i2.value); break; case 2://减 d1.innerText = parseFloat(i1.value)-parseFloat(i2.value); break; case 3://乘 d1.innerText = parseFloat(i1.value)*parseFloat(i2.value); break; case 4://除 d1.innerText = parseFloat(i1.value)/parseFloat(i2.value); break; } } </script> </head> <body> <input type="text" id="i1"> <input type="text" id="i2"> <input type="button" value="加" onclick="fn(1)"> <input type="button" value="减" onclick="fn(2)"> <input type="button" value="乘" onclick="fn(3)"> <input type="button" value="除" onclick="fn(4)"> <div id="d1"></div> </body> </html>