0

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>
4

3 に答える 3

2

ページ上の要素が読み込まれない前にJavaScriptが実行されている可能性があるため、セレクターは何も検出しません。あなたのJavaScriptは<body>タグの上にありますか?後に置いてみて、それが</body>どのように機能するかを確認してください。

別の解決策は次のことです。

window.onload = function () {
//put all your JS here
}
于 2010-11-14T20:37:47.153 に答える
1
onload = function() {
 // put you code here
}
于 2010-11-14T20:37:48.623 に答える
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イベントを使用することもできます。これは、より適切な方法です。

于 2010-11-14T20:40:35.623 に答える