javascript 未捕获的类型错误:无法读取 null 的属性“值”,元素确实存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32758687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uncaught TypeError: Cannot read property 'value' of null, Element does exist
提问by Akshay
Before you downvote, I've read a lot of questions and it didn't help me.
My Javascript's alert
returns null even when there is a value in the input type.
在你投反对票之前,我已经阅读了很多问题,但对我没有帮助。alert
即使输入类型中有值,我的 Javascript 也返回 null。
Here's the code :-
这是代码:-
<script>
if (document.getElementById('p0002') != null) {
var str = document.getElementById("p0002").value;
}
else {
var str = null;
}
alert(str);
</script>
<input type="hidden" name="p0002" id="p0002" value="1" >
<input type="hidden" name="p0003" id="p0003" value="0" >
<input type="hidden" name="p0004" id="p0004" value="2" >
It always returns null
. The error in console says :
它总是返回null
。控制台中的错误说:
Uncaught TypeError: Cannot read property 'value' of null
未捕获的类型错误:无法读取 null 的属性“值”
Trying to fix it since last 1 hour. What is wrong here?
自过去 1 小时以来一直在尝试修复它。这里有什么问题?
回答by Konstantin Dinev
Wrap your JavaScript
in window.onload
. Currently your JavaScript
is executing before the element exists:
把你JavaScript
的window.onload
. 目前您JavaScript
正在元素存在之前执行:
<script>
window.onload = function () {
if (document.getElementById('p0002') != null) {
var str = document.getElementById("p0002").value;
}
else {
var str = null;
}
alert(str);
}
</script>
Another thing you can do is move the script tag to be after the elements you're referencing:
您可以做的另一件事是将脚本标记移动到您引用的元素之后:
<input type="hidden" name="p0002" id="p0002" value="1" >
<input type="hidden" name="p0003" id="p0003" value="0" >
<input type="hidden" name="p0004" id="p0004" value="2" >
<script>
if (document.getElementById('p0002') != null) {
var str = document.getElementById("p0002").value;
}
else {
var str = null;
}
alert(str);
</script>
回答by Alexandr Lazarev
Your script should be excuted after inputs being added to DOM. The most crossbrowser way to make your script work, is to move it just before your <body>
tag is closed, and wrap it into an immediate function:
在将输入添加到 DOM 后,您的脚本应该被执行。让你的脚本工作的最跨浏览器的方式是在你的<body>
标签关闭之前移动它,并将它包装成一个即时函数:
<script>
(function() {
if (document.getElementById('p0002') != null) {
var str = document.getElementById("p0002").value;
} else {
var str = null;
}
alert(str);
})();
</script>
</body>
This is faster to execute than an onload
handler because this waits only for the DOM to be ready, not for all images to load. And, this works in every browser.
这比onload
处理程序执行速度更快,因为它只等待 DOM 准备就绪,而不是所有图像都加载完毕。而且,这适用于所有浏览器。
回答by Harsh Makani
Here your script should be after html.
这里你的脚本应该在 html 之后。