为什么当我对值(见下文)进行警报
时,它返回null
?当具有该 ID 的元素存在时?
// make reference to divs
var countdown_timer = document.getElementById("countdown_timer");
var countdown_image = document.getElementById("countdown_image");
// For element manipulation
if (type == 'image') {
var element = countdown_image;
} else if (type == 'timer') {
var element = countdown_timer;
}
alert(countdown_timer);
div如下..
<div class="timer" id="countdown_timer"></div>
最佳答案
有可能在页面上的元素未加载之前就执行了 JavaScript,因此选择器找不到任何内容。你的javascript是在<body>
之上吗?标签?尝试将其放在 </body>
之后看看它对您有何作用。
另一个解决方案是:
window.onload = function () {
//put all your JS here
}
关于javascript - 为什么我的元素为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4179556/