解释我为什么这个工程,当我点击按钮。javascript:getElementById没有找到元素
<script type="text/javascript">
function myFunction() {
if (screen.width <= 800) {
document.getElementById('cover-img').style.display = 'none';
}
}
</script>
<input type="submit" onclick="myFunction()">
虽然这并不:
<script type="text/javascript">
if (screen.width <= 800) {
document.getElementById('cover-img').style.display = 'none';
}
</script>
它会返回错误:
Uncaught TypeError: Cannot read property 'style' of null
第二个在页面加载时正在运行,因此您可能在该元素存在之前的'
'中有脚本。将脚本移到“”之前,它应该可以工作。 – 2016-06-10 14:09:25可能是因为在执行脚本时不存在cover-img – Li357
[为什么jQuery或诸如getElementById的DOM方法未找到该元素?](http://stackoverflow.com/questions/ 14028959/why-does-jquery-or-a-dom-method-such-getelementbyid-not-the-element) – Xufox