链接外部js文件顺序,出现Uncaught TypeError: Cannot set property 'innerHTML' of null
应当注意JS文件的引用顺序
html文件:
<script type = "text/javascript" src = "js-image.js"></script>
<body>
<div>
<p id = "color>测试文字</p>
</div>
</body>
js文件:
document.getElementById("color").innerHTML = "1newteext";
这样会报错误:Uncaught TypeError: Cannot set property 'innerHTML' of null
因为js引用了下面<div>中的元素,如果<置于<div>之上,是引用不了其中的元素的,应当将其置于最底层的<body>
修改如下,即不会再报错了
html修改文件:
<body>
<div>
<p id = "color>测试文字</p>
</div>
<script type = "text/javascript" src = "js-image.js"></script>
</body>