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

点击计算按钮出现Uncaught TypeError错误,请求代码问题排查

问题根源

你调用document.getElementById()时,传的参数没加引号!比如document.getElementById(height)里的height会被JS当成未定义的变量,而不是你要找的元素ID字符串,导致找不到元素返回null,之后读取null.value就触发了那个类型错误。

修正方案

把所有传给getElementById()的ID参数用单/双引号括起来,同时可以直接复用已经获取到的元素变量,不用重复调用方法:

修正后的JS代码

function calculate() {
    var heightVar = document.getElementById('height');
    var widthVar = document.getElementById('width');
    var lengthVar = document.getElementById('length');
    var piecesVar = document.getElementById('pieces');

    alert(heightVar.value);
}

完整修正后的页面代码

<table>
    <tr>
        <th>Height (inches)</th>
        <th>Width (inches)</th>
        <th>Length (inches)</th>
        <th>Pieces</th>
        <th>Bd Ft</th>
        <th>Lineal Ft</th>
        <th>Sqare Ft</th>
    </tr>
    <tr>
        <td>
            <input type="text" value="1" id="height" /></td>
        <td>
            <input type="text" value="1" id="width" /></td>
        <td>
            <input type="text" value="1" id="length" /></td>
        <td>
            <input type="text" value="1" id="pieces" /></td>
        <td>
            <input type="text" value="" id="bdft" /></td>
        <td>
            <input type="text" value="" id="linealft" /></td>
        <td>
            <input type="text" value="" id="sqft" /></td>
    </tr>
</table>
<input type="button" value="Calculate" onclick="calculate()" />
<script type="text/javascript">
    function calculate() {
        var heightVar = document.getElementById('height');
        var widthVar = document.getElementById('width');
        var lengthVar = document.getElementById('length');
        var piecesVar = document.getElementById('pieces');

        alert(heightVar.value);
    }
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 12:25:02