You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现3文本框计算器:不同按钮输入对应指定文本框?

实现三文本框计算器:让按钮输入对应到指定文本框

你的核心需求是把数字和操作符分别输入到num1、num2两个输入框,最后在answer中展示计算结果。现有代码的问题在于所有数字都默认输入到num1,操作符错误地跑到了answer里——我们需要通过状态跟踪来控制输入目标,下面是完整的解决方案:

核心思路

添加一个状态变量记录当前应该输入数字的文本框,默认是num1;当点击操作符后,切换输入目标到num2;最后根据两个输入框的数字和选中的操作符计算结果。

修改后的完整代码

<!DOCTYPE html>
<html>
<head>
  <title>Simple Calculator</title>
  <style>
    table {
      border-collapse: collapse;
      background: #f0f0f0;
      padding: 10px;
      border-radius: 8px;
    }
    input[type="text"] {
      width: 220px;
      padding: 8px;
      margin: 5px 0;
      font-size: 18px;
    }
    input[type="button"] {
      width: 50px;
      height: 40px;
      margin: 2px;
      font-size: 16px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }
    .heading {
      font-size: 20px;
      font-weight: bold;
      padding: 10px 0;
      text-align: center;
    }
  </style>
</head>
<body>
  <center>
    <table>
      <tr>
        <td class="heading">Simple Math Calculator</td>
      </tr>
      <tr>
        <td>
          <input type="text" id="num1" style="text-align: right;" placeholder="第一个数字"><br>
          <input type="text" id="num2" style="text-align: right;" placeholder="第二个数字"><br>
          <input type="text" id="answer" readonly="readonly" style="color: green; text-align: right;" placeholder="结果">
        </td>
      </tr>
      <tr>
        <td>
          <input type="button" value="CE" onclick="clearScreen()" style="color: white; background: red;">
          <input type="button" value="&#247;" onclick="getOperand('/')">
          <input type="button" value="x" onclick="getOperand('x')">
          <input type="button" value="&#8592;" onclick="backspace()" style="color: red;"><br>
          <input type="button" value="1" onclick="getNumber(1)">
          <input type="button" value="2" onclick="getNumber(2)">
          <input type="button" value="3" onclick="getNumber(3)">
          <input type="button" value="+" onclick="getOperand('+')"><br>
          <input type="button" value="4" onclick="getNumber(4)">
          <input type="button" value="5" onclick="getNumber(5)">
          <input type="button" value="6" onclick="getNumber(6)">
          <input type="button" value="-" onclick="getOperand('-')"><br>
          <input type="button" value="7" onclick="getNumber(7)">
          <input type="button" value="8" onclick="getNumber(8)">
          <input type="button" value="9" onclick="getNumber(9)">
          <input type="button" value="+/-" onclick="getOperand('+/-')"><br>
          <input type="button" value="0" onclick="getNumber(0)">
          <input type="button" value="=" onclick="compute()" style="width: 120px; color: white; background: green;"><br>
        </td>
      </tr>
    </table>
  </center>

  <script>
    // 跟踪当前输入的目标文本框,默认是num1
    let currentInput = 'num1';
    // 暂存选中的操作符
    let operator = '';

    function getNumber(num) {
      // 根据当前状态获取对应的输入框
      const inputBox = document.getElementById(currentInput);
      const numStr = num === 0 ? '0' : num.toString();
      inputBox.value += numStr;
    }

    function getOperand(operand) {
      // 若第一个数字为空,不允许输入操作符
      if (document.getElementById('num1').value === '') return;

      // 处理正负号切换:给当前输入框的数字添加/移除负号
      if (operand === '+/-') {
        const inputBox = document.getElementById(currentInput);
        inputBox.value = inputBox.value 
          ? (inputBox.value.startsWith('-') ? inputBox.value.slice(1) : '-' + inputBox.value) 
          : '';
        return;
      }

      // 记录操作符(把x转为JS的乘号*)
      operator = operand === 'x' ? '*' : operand;
      // 切换输入目标到第二个数字框
      currentInput = 'num2';
    }

    function clearScreen() {
      // 清空所有输入框
      document.getElementById('num1').value = '';
      document.getElementById('num2').value = '';
      document.getElementById('answer').value = '';
      // 重置状态
      currentInput = 'num1';
      operator = '';
    }

    function backspace() {
      // 给当前输入的文本框做退格操作
      const inputBox = document.getElementById(currentInput);
      inputBox.value = inputBox.value.slice(0, -1);
    }

    function compute() {
      const num1 = parseFloat(document.getElementById('num1').value);
      const num2 = parseFloat(document.getElementById('num2').value);
      let result;

      // 检查输入是否为有效数字
      if (isNaN(num1) || isNaN(num2)) {
        document.getElementById('answer').value = '无效输入';
        return;
      }

      // 根据操作符计算结果
      switch(operator) {
        case '+':
          result = num1 + num2;
          break;
        case '-':
          result = num1 - num2;
          break;
        case '*':
          result = num1 * num2;
          break;
        case '/':
          // 处理除数为0的异常情况
          result = num2 === 0 ? '不能除以0' : num1 / num2;
          break;
        default:
          result = '请输入操作符';
      }

      document.getElementById('answer').value = '= ' + result;
    }
  </script>
</body>
</html>

关键逻辑说明

  1. 状态变量currentInput:控制数字按钮的输入目标,默认指向num1,点击操作符后切换到num2,确保数字输入到正确的位置。
  2. 操作符处理:单独处理+/-按钮(直接切换当前输入框数字的正负),其他操作符则记录并切换输入状态。
  3. 计算逻辑:从两个输入框获取数值,通过switch判断操作符计算结果,避免了eval的安全风险,同时处理了无效输入和除数为0的异常场景。

内容的提问来源于stack exchange,提问作者Amateurprogrammer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 15:37:33