<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>我的网页</title> <style> #tab1{ width: 300px; background-color: pink; padding: 20px; } </style> <script> /* //var a = new Date(); //alert(a); console.log(typeof a);//判断值的类型 /* * 定义两数相加的方法 * .trim前后两端空格 */ //自定义函数传参 function calculate(op){ //将传进来的值去空格(是两端空格); var cal=op.value.trim(); //获取到num1的值并去掉空格 var num1=document.getElementById("num1").value.trim(); //获取到num2的值并去掉空格 var num2=document.getElementById("num2").value.trim(); //判断值的长度 if(num1.length==0||num2.length==0){ alert("不能为空"); return; } //判断是不是数字 if(isNaN(num1) || isNaN(num2)){ alert("不是数字"); return; } var result; switch(cal){//将传进来的值进行匹配 case '+': result=parseFloat(num1)+parseFloat(num2); break; case '-': result=parseFloat(num1)-parseFloat(num2); break; case '×': result=parseFloat(num1)*parseFloat(num2); break; case '÷': result=parseFloat(num1)/parseFloat(num2); break; } //将获取到的值赋给result;并将获得的值保留两位小数; document.getElementById("result").value=result.toFixed(2); } </script> </head> <body> <table id="tab1" > <tr><th colspan="4">计算器</th></tr> <tr> <th>第一个数:</th> <td colspan="3"><input id="num1" /></td> </tr> <tr> <th>第二个数:</th> <td colspan="3"><input id="num2"/></td> </tr> <tr> <td ><input type="button" value="+" onclick="calculate(this)"/></td> <td ><input type="button" value="-" onclick="calculate(this)"/></td> <td ><input type="button" value="×" onclick="calculate(this)"/></td> <td ><input type="button" value="÷" onclick="calculate(this)"/></td> </tr> <tr> <th>结 果:</th> <td colspan="3"><input id="result"/></td> </tr> </table> </body> </html>
Javascript写一个简单的计算器
猜你喜欢
转载自blog.csdn.net/lzpzwy/article/details/80072688
今日推荐
周排行