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

HTML input计算器返回[object HTMLInputElement]及jQuery实现咨询

问题根因
  • 你代码中直接把document.getElementById获取到的<input> DOM对象做加法运算,JS会默认将对象转为字符串[object HTMLInputElement]后拼接,因此输出你遇到的结果
  • 正确实现需要先读取input元素的value属性,再转为数值类型后再执行计算
原生JS修正代码
<html>
<head>
</head>
<body>
        <input id="nume" type="number">
        <input id="num" type="number">
        <input type="button" onclick="MyFunction()" value="Click to calculate">
        <p id="f">Value Is: 0</p>
</body>
<script>
    const something = document.getElementById("nume")
    const somethingElse = document.getElementById("num")
    function MyFunction(){
        // 读取输入值并转为数字,空输入默认取0
        const num1 = Number(something.value) || 0
        const num2 = Number(somethingElse.value) || 0
        const values = num1 + num2;
        document.getElementById("f").innerHTML = "Value Is: " + values
    }
</script>
</html>
jQuery实现版本

使用前需要先在页面引入jQuery库,实现代码如下:

<html>
<head>
    <!-- 此处需先引入jQuery库,可使用本地存放的jQuery文件或公共CDN资源 -->
</head>
<body>
        <input id="nume" type="number">
        <input id="num" type="number">
        <input type="button" id="calcBtn" value="Click to calculate">
        <p id="f">Value Is: 0</p>
</body>
<script>
// 等待DOM加载完成后绑定点击事件
$(function(){
    $('#calcBtn').click(function(){
        // 用jQuery的val()方法获取输入值,转为数字,空输入默认取0
        const num1 = Number($('#nume').val()) || 0
        const num2 = Number($('#num').val()) || 0
        $('#f').text('Value Is: ' + (num1 + num2))
    })
})
</script>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 12:45:02