当前位置: 代码迷 >> 综合 >> JavaScript编写简单计算器
  详细解决方案

JavaScript编写简单计算器

热度:78   发布时间:2023-09-20 23:31:01.0
<html><head><title>简单计算器</title></head><body><fieldset><legend>计算器</legend><form name="opeform">第一个数:<input type="text" name="n1"><br>运算符号:<select name="operator"><option value="append">+</option><option value="subtract">-</option><option value="multiply">*</option><option value="divide">/</option></select><br>第二个数:<input type="text" name="n2"><br>等于号:<input type="button" value="=" name="equal" οnclick="operate()"><br>结    果:<input type="text" name="result" id="r1"></form></fieldset><script>//获取下拉列表的值function getSel(obj){var _select=obj,i      =0,size   =_select.length;for(;i<size;i++){if(_select[i].checked){return _select[i].value;}}}//计算器:当点击等于号时处理运算结果function operate(){var result,//结果num1=document.opeform.n1.value,//获取第一个文本框的值num2=document.opeform.n2.value,//获取第二个文本框的值 _operator=document.opeform.operator.value;//获取运算符if(!(isNaN(num1) && isNaN(num2))){//判断是否是数字num1=parseFloat(num1);//转为浮点型num2=parseFloat(num2);switch (_operator) {case "append":result=num1+num2;document.opeform.result.value=result;//把结果赋值给结果文本框break;case "subtract":result=num1-num2;document.opeform.result.value=result;break;case "multiply":result=num1*num2;document.opeform.result.value=result;break;default:if(num2==0){alert("除数不能为零!");}else {result=num1/num2;document.opeform.result.value=result;}break;}}else{alert("请输入数字!");	}    }</script></body>
</html>

  相关解决方案