将文本/元素附加到 DIV 标记
如何使用 getElementById
将文本/元素添加到目标元素(div)(不带 jquery) 页面加载时?
这是我当前的标记:
<html>
<head>
<title>test</title>
<script language="javascript">
/document.getElementById('content').innerHTML = 'Fred Flinstone';
</script>
</head>
<body>
<div id="content">
dssdfs
</div>
</body>
</html>
How do I add text/elements to a target element (div) using getElementById
(without jquery) when the page loads?
Here's my markup currently:
<html>
<head>
<title>test</title>
<script language="javascript">
/document.getElementById('content').innerHTML = 'Fred Flinstone';
</script>
</head>
<body>
<div id="content">
dssdfs
</div>
</body>
</html>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为发生的情况是您的脚本在文档准备好之前就已执行。尝试将您的 JavaScript 放入正文加载事件中。
I think what is happening is that your script is executing before your document is ready. Try placing your javascript in a body load event.
最快(尽管不是最好)的方法是将脚本块放在 HTML 文件的末尾(在您要修改的
之后)。
更好的方法是注册 DOM 加载通知
如果您希望它在页面加载后执行,那么您需要观察 DOM 加载事件。您可以通过在脚本块中订阅 DOM 加载事件,然后将操作 DIV 的代码放入事件处理程序中来完成此操作。
棘手的部分是,不同的浏览器可能需要稍微不同的方式来注册,以便在加载 DOM 时收到通知(这就是 jQuery 或不同的库变得有用)。
以下是有关注册在 DOM 加载时调用的回调的不同方法的更多信息DOM 已加载。这些信息可能有点过时,因为流行浏览器的更现代版本现在已经变得更加符合标准:http://www.javascriptkit.com/dhtmltutors/domready.shtml
The quickest (although not the best) way to do it is to put your script block towards the end of the HTML file (after the
<div>
you wish to modify).The better way to do it is to register for DOM load notification
If you want it to execute after the page loads, then you need to observe the DOM loaded event. You can do that by subscribing to the DOM load event in the script block and then put the code that manipulates the DIV in the event handler.
The tricky part is that different browsers may need slightly different ways to register to be notified when the DOM is loaded (that's were jQuery or a different library becomes useful)
Here's some more information about different ways to register for a callback to be called when the DOM is loaded. The information may be a bit out of date as more modern versions of the popular browsers have become more standards compliant now: http://www.javascriptkit.com/dhtmltutors/domready.shtml