Javascript 为什么我的元素为空?

Javascript 为什么我的元素为空?,javascript,null,getelementbyid,Javascript,Null,Getelementbyid,为什么当我对值(见下文)发出警报时,它会返回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') {

为什么当我对值(见下文)发出
警报时,它会返回
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 class="timer" id="countdown_timer"></div>

可能是在未加载页面上的元素之前执行javascript,因此选择器找不到任何内容。您的javascript是否在
标记之上?试着把它放在
后面,看看它对你有什么作用

另一个解决方案是:

window.onload = function () {
//put all your JS here
}

javascript可能是在页面上的元素未加载之前执行的,因此选择器找不到任何东西。您的javascript是否在
标记之上?试着把它放在
后面,看看它对你有什么作用

另一个解决方案是:

window.onload = function () {
//put all your JS here
}

document.getElementById
的调用需要在div的标记之后

<div class="timer" id="countdown_timer"></div>
<script type="text/javascript">
var countdown_timer = document.getElementById("countdown_timer");
 ...
</script>

var countdown_timer=document.getElementById(“countdown_timer”);
...

或者,您可以使用window.onload事件,这是更好的方法。

文档的调用。getElementById
需要在div的标记之后

<div class="timer" id="countdown_timer"></div>
<script type="text/javascript">
var countdown_timer = document.getElementById("countdown_timer");
 ...
</script>

var countdown_timer=document.getElementById(“countdown_timer”);
...

或者,您可以使用window.onload事件,哪种方法更好。

确保在相关元素被解析并插入DOM后调用
document.getElementById
。的可能重复项确保在相关元素被解析并插入DOM后调用
document.getElementById
。的可能重复项是 啊我在页面的主体部分调用javascript,但在元素之上。。。。。将它移到它们下面&它起作用了!:)是 啊我在页面的主体部分调用javascript,但在元素之上。。。。。将它移到它们下面&它起作用了!:)是的。。。。就在我看到你的答案被其他答案取代之前,我把它整理好了哈哈:)是的。。。。就在我看到你的答案被其他答案取代之前,我把它整理好了哈哈:)