通过js实现一个可以完成加减乘除的简易计算器。代码如下:

<!DOCTYPE html>
<html>
 <head>
  <title> 事件</title>  
  <script type="text/javascript">
   function count(){
    var first= document.getElementById("txt1").value;
    var  second=document.getElementById("txt2").value;
    var  selection=document.getElementById("select").value;
    var outcome=0;
    //获取第一个输入框的值
	//获取第二个输入框的值
	//获取选择框的值
	//获取通过下拉框来选择的值来改变加减乘除的运算法则
    //设置结果输入框的值  
    
    if(selection=="+"){
       outcome=parseInt(first)+parseInt(second);
    }
    else if(selection=="-"){
         outcome=parseInt(first)-parseInt(second);
    }
    else if(selection=="*"){
         outcome=parseInt(first)*parseInt(second);
    }
    else if(selection=="/"){
         outcome=parseInt(first)/parseInt(second);
    }
 
    document.getElementById("fruit").value=outcome;
   }
  </script> 
 </head> 
 <body>
   <input type='text' id='txt1' /> 
   <select id='select'>
		<option value='+'>+</option>
		<option value="-">-</option>
		<option value="*">*</option>
		<option value="/">/</option>
   </select>
   <input type='text' id='txt2' /> 
   <input type='button' value=' = ' onclick="count()" /> <!--通过 = 按钮来调用创建的函数,得到结果--> 
   <input type='text' id='fruit' />   
 </body>
</html>

代码解释:

 var first= document.getElementById("txt1").value 是对id为“txt1”的文本框赋值,当往文本框里输入值时就赋给first变量,后面同理;

if  else 语句就是判断选择的是什么种类的运算符号,从而进行对应的运 算, outcome=parseInt(first)/parseInt(second); 其中的parseInt的作用是解析一个字符串,并返回一个整数,再将outcome赋值给结果文本框。

最后通过设置一个value为“=”的按钮绑定count函数即可,请看结果:

加法:

减法:

乘法:

除法: 

更多推荐

js之实现一个简易的计算器