javascript位置错误导致Uncaught TypeError: Cannot read property 'elements' of null
2018-01-21 20:50
1951 查看
在学习js的表单脚本的时候,写了一个取表单字段的demo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
var form=document.getElementById("myForm");
var field=form.elements[0];
alert(field);
</script>
</head>
<body>
<form method="post" id="myForm">
<ul>
<li><input type="radio" name="color" value="red">Red</li>
<li><input type="radio" name="color" value="green">Green</li>
<li><input type="radio" name="color" value="blue">Blue</li>
</ul>
</form>
</body>
</html>
发现浏览器报错如下:Uncaught TypeError: Cannot read property 'elements' of null,发现原来是js代码的位置放错了,JS运行的时候页面还没有加载完成,所以JS代码找不到页面元素,就会抛出这个问题。将js代码放在body最后就ok了。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
var form=document.getElementById("myForm");
var field=form.elements[0];
alert(field);
</script>
</head>
<body>
<form method="post" id="myForm">
<ul>
<li><input type="radio" name="color" value="red">Red</li>
<li><input type="radio" name="color" value="green">Green</li>
<li><input type="radio" name="color" value="blue">Blue</li>
</ul>
</form>
</body>
</html>
发现浏览器报错如下:Uncaught TypeError: Cannot read property 'elements' of null,发现原来是js代码的位置放错了,JS运行的时候页面还没有加载完成,所以JS代码找不到页面元素,就会抛出这个问题。将js代码放在body最后就ok了。
相关文章推荐
- Uncaught TypeError: Cannot read property 'getElementsByTagName' of null
- canvas出现Uncaught TypeError: Cannot read property 'getContext' of null 错误
- 错误码:Uncaught TypeError: Cannot read property 'field' of undefined
- test_canvas.js:15 Uncaught TypeError: Cannot read property 'getContext' of null
- Android Webview: “Uncaught TypeError: Cannot read property 'getItem' of null”
- 错误:Uncaught TypeError: Cannot read property 'WebSocket' of undefined
- JavaScript:Uncaught TypeError Cannot read property 'id' of null。
- javascript Uncaught TypeError: Cannot read property ... of undefined
- Uncaught TypeError: Cannot read property 'options' of undefined 错误
- Uncaught TypeError: Cannot read property 'childNodes' of null
- JS —— Uncaught TypeError: Cannot read property 'slice' of undefined 错误
- Uncaught TypeError: Cannot read property 'drawImage' of undefined错误的解决办法
- Uncaught TypeError: Cannot read property 'length' of undefined
- TypeError: Cannot read property 'style' of null 错误解决
- echarts.js:24938 Uncaught TypeError: Cannot read property '0' of undefined
- H5拖放事件 "Uncaught TypeError: Cannot read property 'setData' of undefined"
- discuz 出现了Uncaught TypeError: Cannot read property 'appendChild' of null
- dataTabel Uncaught TypeError: Cannot read property 'asSorting' of undefined
- Uncaught TypeError: Cannot read property 'prototype' of null using Openerp 7.0
- 【Angular2】Uncaught (in promise): TypeError: Cannot read property 'id'