欢迎来到HELLO素材网!
丰富的DIV CSS模版、JS,jQuery特效免费提供下载
当前位置:主页 > 建站教程 > JS教程 >

JavaScript计算器实例

发表于2014-06-03 21:28| 次阅读| 来源整理| 作者管理员

摘要:用JavaScript实现的一个简单计算器,可以计算两个数之间的加减乘除。

JavaScript代码


<script type="text/javascript">
var calc = {
 first:0,
 second:0,
 result:0,
 init:function(){
  this.first = parseFloat(document.getElementById("first").value);
  this.second = parseFloat(document.getElementById("second").value);
 },
 setResult:function(){document.getElementById("result").value = this.result},
 add:function(){ 
   this.init();
   this.result = this.first + this.second;
   this.setResult();
   },
 minus:function(){ 
   this.init();
   this.result = this.first - this.second;
   this.setResult();
   },
 plus:function(){ 
   this.init();
   this.result = this.first * this.second;
   this.setResult();
   },
 divide:function(){ 
   this.init();
   this.result = this.first / this.second;
   this.setResult();
   }
};
</script>


HTML代码


<form id="jisuanqi" action="#">
      <p>
        <label for="first">数字1:</label>
        <input id="first" type="text">
      </p>
      <p>
        <label for="second">数字2:</label>
        <input id="second" type="text">
      </p>
      <p>
        <label for="result">结果:</label>
        <input id="result" type="text">
      </p>
      <br><button onclick="calc.add();;return false;" value="加">加</button>
      <button onclick="calc.minus();;return false;" value="减">减</button>
      <button onclick="calc.plus();;return false;" value="乘">乘</button>
      <button onclick="calc.divide();;return false;" value="除">除</button>
      </form>


效果



运行代码保存代码提示:您可以先修改部分代码再运行