Javascript 无法通过 id 找到元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4498482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript can't find element by id?
提问by Bluemagica
<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>
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?
如果我使用alert(e);
它会出现null
......显然我没有在屏幕上看到任何“找到你”。我究竟做错了什么?
回答by jwueller
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:
问题是您试图在元素存在之前访问它。您需要等待页面完全加载。一种可能的方法是使用onload
处理程序:
window.onload = function () {
var e = document.getElementById("db_info");
e.innerHTML='Found you';
};
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.
不过,大多数常见的 JavaScript 库都提供了 DOM 就绪事件。这更好,因为也window.onload
等待所有图像。在大多数情况下,您不需要这样做。
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.
另一种方法是将脚本标记放在结束标记之前</body>
,因为它前面的所有内容都在执行时加载。
回答by dheerosaur
How will the browser know when to run the code inside script tag? So, to make the code run after the window is loaded completely,
浏览器如何知道何时运行脚本标签内的代码?因此,要在窗口完全加载后运行代码,
window.onload = doStuff;
function doStuff() {
var e = document.getElementById("db_info");
e.innerHTML='Found you';
}
The other alternative is to keep your <script...</script>
just before the closing </body>
tag.
另一种选择是<script...</script>
在结束</body>
标签之前保留您的标签。
回答by Dave
Script is called before element exists.
在元素存在之前调用脚本。
You should try one of the following:
您应该尝试以下方法之一:
- wrap code into a function and use a body onload event to call it.
- put script at the end of document
- use defer attribute into script tag declaration
- 将代码包装到一个函数中并使用主体 onload 事件来调用它。
- 将脚本放在文档末尾
- 在脚本标签声明中使用 defer 属性
回答by Ionu? Staicu
Run the code either in onload event, either just before you close body
tag.
You try to find an element wich is not there at the moment you do it.
在 onload 事件中运行代码,或者在关闭body
标签之前运行。你试图找到一个在你做的那一刻不存在的元素。
回答by sjngm
The script is performed before the DOM of the body is built. Put it all into a function and call it from the onload
of the body-element.
该脚本在构建主体的 DOM 之前执行。将其全部放入一个函数中并从onload
body 元素的 中调用它。