未捕获的类型错误:不能读取属性'元素不存在
Uncaught TypeError: Cannot read property 'value' of null, Element does exist
在你拒绝投票之前,我读了很多问题,但它没有帮助我。我的Javascript的alert
返回null,即使在输入类型中有一个值。
代码如下:-
<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" >
它总是返回null
。控制台错误提示:
Uncaught TypeError: Cannot read property 'value' of null
尝试修复它从过去的1小时。这里出了什么问题?
将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>
你可以做的另一件事是将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" >
<script>
if (document.getElementById('p0002') != null) {
var str = document.getElementById("p0002").value;
}
else {
var str = null;
}
alert(str);
</script>
脚本应该在输入被添加到DOM后执行。使脚本工作的最跨浏览器的方法是在关闭<body>
标记之前移动它,并将其包装成一个直接函数:
<script>
(function() {
if (document.getElementById('p0002') != null) {
var str = document.getElementById("p0002").value;
} else {
var str = null;
}
alert(str);
})();
</script>
</body>
这比onload
处理程序执行得更快,因为它只等待DOM准备好,而不是等待所有图像加载。而且,这适用于所有浏览器。
你的脚本应该在html之后
相关文章:
- TypeError:无法读取属性'推'未定义的JavaScript
- 同样,同样的错误'ahorcado.js:26未捕获类型错误:无法读取属性'beginPath'
- 未捕获的TypeError无法读取未定义的属性socialsharing
- 未捕获的类型错误:无法读取属性'删除'的未定义
- AngularJS指令出错-无法读取属性'编译'的未定义
- 未捕获的类型错误:无法读取属性'name'即使它存在,也无法定义
- 看到“;未捕获的类型错误:无法读取属性'weight'未定义的“;尽管按照字面上的指示
- angularjs无法读取未定义的属性then
- 无法读取属性'材料'未定义的Three.js
- 得到"TypeError:无法读取属性'filename'未定义的“;调用“npm start
- Soundcloud api"未捕获的类型错误:无法读取属性'uri'“未定义”;
- 未捕获的类型错误:无法读取属性'addEventListener'的null chrome扩展名
- Soundcloud Javascript SDK 3.0-回调无法读取属性'connectCallback
- 未捕获的类型错误:无法读取属性'状态'在react中为null
- JavaScript承诺-无法读取属性'那么'的未定义
- Javascript Float32数组抛出无法读取属性'0'即使数组定义良好,也为null
- 未捕获的类型错误:无法读取属性'中止'的未定义
- 角度推入数组给出:TypeError:无法读取属性'推'的未定义
- http/rxjs catch回调中的Angular 2重定向导致TypeError:无法读取属性'订阅'
- 角度输入模型有条件地从一个属性读取,写入另一个属性