JavaScript实现简易计算器:HTML表单与JS逻辑详解

作者:页面旅途

时间:2026-10-24

浏览:342

本文介绍如何使用HTML和JavaScript构建一个简易计算器。通过创建包含两个输入框和四个运算按钮的表单,利用onclick事件触发统一的cal()函数。该函数通过switch语句处理加减乘除逻辑,获取用户输入并显示结果,适合初学者学习前端交互与基础算法。

文章目录

JavaScript简易计算器实现概述

本文分享了一段使用JavaScript编写的简易计算器代码示例,供读者参考学习。

JavaScript简易计算器实现概述

HTML表单结构构建

实现如图所示的简易计算器,首先需要构建相应的HTML表单,还原界面布局。


<table border="1" cellspacing="0" >
   <tr><th colspan="2">购物简易计算器</th></tr>
   <tr>
    <td>第一个数</td>
       <td><input type="text" id="inputId1" /></td>
   </tr>
   <tr>
    <td>第二个数</td>
       <td><input type="text" id="inputId2" /></td>
   </tr>
   <tr>
    <td><button type="button" onclick="cal('+')" >+</button></td>
    <td><button type="button" onclick="cal('-')" >-</button>
    <button type="button" onclick="cal('*')" >*</button>
    <button type="button" onclick="cal('/')" >/</button></td>
   </tr>
   <tr>
    <td>计算结果</td>
    <td><input type="text" id="resultId"/></td>
   </tr>
</table>

JavaScript核心逻辑与优化

在按钮点击事件中调用cal()函数。起初曾考虑分别编写add、sub、mul、div四个独立方法,但发现它们仅算术运算符不同,其余逻辑一致。因此优化为单一方法,通过点击按钮传递不同的运算符参数,具体实现代码如下:


<script type="text/javascript">
 function cal(type){
  var num1 = document.getElementById('inputId1');
  var num2 = document.getElementById('inputId2');
  var result;
   switch(type){
    case '+':
    result = parseInt(num1.value) + parseInt(num2.value);
    break;
    case '-':
    result = parseInt(num1.value) - parseInt(num2.value);
    break;
    case '*':
    result = parseInt(num1.value) * parseInt(num2.value);
    break;
    case '/':
    result = parseInt(num1.value) / parseInt(num2.value);
    break;
  }
 var resultObj = document.getElementById('resultId');
 resultObj.value = result;
 }
</script>

总结

以上内容即为本文的全部分享,希望能为读者的学习提供有益帮助,同时也感谢大家的支持。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章