点击计算按钮出现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
相关产品推荐
相关产品推荐

