用 javascript 操作 dom 时出现如下错误:
uncaught typeerror: cannot set property 'value' of null uncaught typeerror: cannot read property 'id' of undefined
例如:
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <script> var div = document.getelementbyid("测试1"); alert(div.id); alert(div.classname); alert(div.title); </script> <title>测试</title> </head> <body> <div id="测试1" class="测试2" title="测试3"> <span>0</span> <span>1</span> <span>2</span> <span>3</span> </div> </body> </html>
运行时出现如下错误:
问题出在 js 运行的时候你的页面还没有加载完成,所以你的 js 代码找不到你的页面元素,就会抛出这个问题。解决办法就是把 javascript 代码放在 body 的最后,例如:
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>测试</title> </head> <body> <div id="测试1" class="测试2" title="测试3"> <span>0</span> <span>1</span> <span>2</span> <span>3</span> </div> <script> var div = document.getelementbyid("测试1"); alert(div.id); alert(div.classname); alert(div.title); </script> </body> </html>
如对本文有疑问, 点击进行留言回复!!
Parallels Desktop 16值得升级吗 Parallels Desktop 16更新内容汇总
网友评论