为什么我的元素为空?

时间:2010-11-14 20:35:10

标签: javascript null getelementbyid

为什么当我执行alert的值(见下文)时,它会返回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>

3 个答案:

答案 0 :(得分:2)

在页面上的元素未加载之前,javascript可能正在执行,因此选择器找不到任何内容。您的JavaScript是否高于<body>标记?尝试将其放在</body>之后,看看它对您有何用处。

另一种解决方案是:

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

答案 1 :(得分:1)

onload = function() {
 // put you code here
}

答案 2 :(得分:0)

您对document.getElementById的呼叫需要在div的标记之后。

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

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

相关问题