解釋我爲什麼這個工程,當我點擊按鈕。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