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

如何为多个输入元素添加事件监听器,实时计算并更新四则运算结果

实现方案

先调整HTML输入框属性(可选,优化体验)

给两个数字输入框添加type="number"限制输入类型,避免用户输入非数字内容:

<div class="form">
  <input class="input" id="firstNum" type="number" />
  <input class="input" id="secondNum" type="number" />
</div>
<!-- 后续grid展示结构保持不变 -->

优化operators.js(增加边界判断)

调整除法逻辑,避免除数为0时出现异常值:

export function addition (a, b) { 
    return parseInt(a) + parseInt(b)
}

export function substraction (a, b) { 
    return parseInt(a) - parseInt(b)
}

export function multiplication (a, b) { 
    return parseInt(a) * parseInt(b)
}

export function division (a, b) { 
    const numB = parseInt(b)
    if (numB === 0) return '除数不能为0'
    return (parseInt(a) / numB).toFixed(1)
}

修正script.js核心逻辑

原有代码核心错误:仅读取了触发事件的输入框ID,没有获取两个输入框的实际数值,且a、b被赋值为同一个值,完全无法正常计算。修正后代码如下:

import * as mathOperator from "./operators.js"

// 给所有输入框绑定监听事件,用input事件可以实时响应输入,不需要等失去焦点
document.querySelectorAll(".input").forEach(function (element) { 
    element.addEventListener("input", function () {
        // 每次输入变化时,统一读取两个输入框的最新数值
        const firstVal = document.getElementById('firstNum').value
        const secondVal = document.getElementById('secondNum').value

        // 校验两个输入框都有值再执行计算
        if (!firstVal || !secondVal) {
            // 任意一个输入为空就清空所有结果
            document.getElementById("addition").textContent = ''
            document.getElementById("substraction").textContent = ''
            document.getElementById("multiplication").textContent = ''
            document.getElementById("division").textContent = ''
            return
        }

        // 传入数值执行计算并更新结果
        document.getElementById("addition").textContent = mathOperator.addition(firstVal, secondVal)
        document.getElementById("substraction").textContent = mathOperator.substraction(firstVal, secondVal)
        document.getElementById("multiplication").textContent = mathOperator.multiplication(firstVal, secondVal)
        document.getElementById("division").textContent = mathOperator.division(firstVal, secondVal)
    })
})

实现逻辑说明

  • 监听所有输入框的内容变化事件,每次触发时统一读取两个输入框的最新值
  • 增加非空校验和除数为0的异常处理,避免出现非法结果
  • 计算完成后直接将结果写入对应展示节点即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 17:27:03