Javascript找不到id的元素? [英] Javascript can't find element by id?
问题描述
<html>
<head>
<title>Test javascript</title>
<script type="text/javascript">
var e = document.getElementById("db_info");
e.innerHTML='Found you';
</script>
</head>
<body>
<div id="content">
<div id="tables">
</div>
<div id="db_info">
</div>
</div>
</body>
</html>
如果我使用 alert(e);
它出现 null
....显然我没有在屏幕上找到任何找到你。我做错了什么?
If I use alert(e);
it turns up null
.... and obviously I don't get any "found you" on screen. What am I doing wrong?
推荐答案
问题是你试图在元素存在之前访问它。您需要等待页面完全加载。一种可能的方法是使用 onload
处理程序:
The problem is that you are trying to access the element before it exists. You need to wait for the page to be fully loaded. A possible approach is to use the onload
handler:
window.onload = function () {
var e = document.getElementById("db_info");
e.innerHTML='Found you';
};
但是,大多数常见的JavaScript库都提供了DOM就绪事件。这是更好的,因为 window.onload
也等待所有图像。在大多数情况下,您不需要这样做。
Most common JavaScript libraries provide a DOM-ready event, though. This is better, since window.onload
waits for all images, too. You do not need that in most cases.
另一种方法是在结束< / body> $之前放置脚本标记c $ c> -tag,因为它前面的所有内容都是在执行时加载的。
Another approach is to place the script tag right before your closing </body>
-tag, since everything in front of it is loaded at the time of execution, then.
这篇关于Javascript找不到id的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!