为什么我的元素为空?
为什么当我对值进行警报
(见下文)时,它返回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>
Why when I do an alert
of the value (see below) it returns null
? When an element with that ID exists?
// 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);
The div is as below..
<div class="timer" id="countdown_timer"></div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
javascript 可能在页面上的元素未加载之前执行,因此选择器找不到任何内容。您的 javascript 是否位于
标记之上?尝试将其放在
之后,看看它对您有何作用。
另一个解决方案是:
It's possible that the javascript is being executed before the elements on your page are not loaded, thus the selector isn't finding anything. Is your javascript above the
<body>
tag? Try putting it after</body>
and see how that works for you.Another solution is to do:
您对
document.getElementById
的调用需要位于 div 标记之后。或者,您可以使用 window.onload 事件,这将是更好的方法。
Your call to
document.getElementById
needs to be after the markup for the div.Alternatively, you could use the window.onload event, which would be the better way to go.