在下面的代码中:
function Transact() {
if(document.getElementById('itctobuy').value!='') {
itctobuy = parseInt(document.getElementById('itctobuy').value);
}
if(document.getElementById('steamtobuy').value!='') {
steamtobuy = parseInt(document.getElementById('steamtobuy').value);
}
if(document.getElementById('reltobuy').value!='') {
reltobuy = parseInt(document.getElementById('reltobuy').value);
}
if(document.getElementById('airtobuy').value!='') {
airtobuy = parseInt(document.getElementById('airtobuy').value);
}
if(document.getElementById('bsnltobuy').value!='') {
bsnltobuy = parseInt(document.getElementById('bsnltobuy').value);
}
updateValues();
}
该功能由按钮的简单
onclick
执行。有5个textarea元素,用户可以在其中输入任何数字,如果textarea值不为空,则单击按钮后,该值应存储在这些var中(尽管即使不为空,也不能使用)当下)。如果我删除了整个块,则
updateValues()
可以很好地执行,而放回原处会导致它不被执行,所以问题就出在这里。这是什么原因,我该如何解决?编辑:控制台显示以下内容:
未被捕获的TypeError:在HTMLButtonElement.onclick上的TRANSACT无法读取null的属性“值”
那么,此错误的原因是什么?当我输入所有文本字段并且它们的值不为null时,它不起作用。
最佳答案
Uncaught TypeError: Cannot read property 'value' of null
这表明在代码运行时这些元素中至少有一个不存在,因此getElementById
返回null
,您正试图从中读取value
属性。
如果在调用文档时文档中不存在具有给定ID的元素,则getElementById
将仅返回null
。通常,不存在该元素的原因可归为以下几类:
太早调用getElementById
id
拼写错误(例如拼写错误)
使用name
代替id
元素存在,但不在文档中(稀有)
在您的情况下,由于这是单击按钮,因此可能是#2或#3。通过查看错误标识的行,或使用浏览器的调试器逐个语句遍历代码,可以了解不满意的ID。
让我们看一下每个类别:
1.呼叫getElementById
太早
一个常见的错误是让代码在HTML元素之前的getElementById
块中调用script
,如下所示:
<script>
document.getElementById("foo").innerHTML = "bar";
</script>
<!-- ...and later... -->
<div id="foo"></div>
该代码运行时该元素不存在。
解决方案:
将
script
移动到HTML的末尾,紧接</body.
标记之前在回调中(例如在
getElementById
事件上,或在按钮上单击),将对DOMContentLoaded
的呼叫置于呼叫中。不要使用
window.onload
或<body onload="...">
,除非您真的想等所有的外部资源(包括所有图像)加载完毕后再运行代码。2.
id
拼写错误当使用
getElementById("ofo")
定义元素时,使用id="foo"
确实很常见。例:
<div id="foo"></div>
<script>
document.getElementById("ofo").innerHTML = "I'm foo"; // Error
</script>
解决方案:使用正确的ID。 :-)
3.使用
name
代替id
getElementById("foo")
使用id="foo"
查找元素,而不使用name="foo"
查找元素。 name
!= id
。例:
<input name="foo" type="text">
<script>
document.getElementById("foo").value = "I'm foo"; // Error
</script>
解决方案:使用
id
,而不是name
。 :-)(或使用document.querySelector('[name="foo"]')
查找元素。)4.元素存在,但不在文档中
getElementById
在文档中查找该元素。因此,如果该元素已创建,但尚未添加到文档中的任何位置,则找不到该元素。例:
var div = document.createElement("div");
div.id = "foo";
console.log(document.getElementById("foo")); // null
它不会在整个内存中查找,而只是在文档中查找(特别是您在其上调用的文档;例如,不同的框架具有不同的文档)。
解决方案:确保元素在文档中;也许您忘了在创建后附加它? (但是在上面的示例中,您已经有了对它的引用,因此根本不需要
getElementById
。)关于javascript - 使用getElementById时,为什么会出现“TypeError:无法读取null的属性'value'”的信息?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40489919/