在html头部的javascript,innerhtml无法正常工作? [英] javascript in html head, innerhtml not working?

查看:91
本文介绍了在html头部的javascript,innerhtml无法正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 <html>
 <head>
 <script type="text/javascript">
 document.getElementById("eee").innerHTML = "7777";
 </script>


 </head>
 <body>
 <p id="eee">aa</p>

 </body>
 </html>

为什么innerHTML不起作用,但它在身体中有效吗?请原谅初学者的问题,但上次我一年前使用javascript这根本不是问题。

why does the innerHTML not work in the head, but it does work in the body? Excuse the beginners question but last time i used javascript a year ago this was not a problem at all.

推荐答案

你需要等待对于HTML文档在被操作之前加载。

You need to wait for the HTML document to be loaded before it can be manipulated.

<script type="text/javascript">
  window.onload = function() {
    document.getElementById("eee").innerHTML = "7777";
  };
</script>

请记住,脚本按照HTML文档中列出的顺序进行评估,因此您的脚本在浏览器处理head部分时运行。由于浏览器尚未解析body部分,因此它不知道ID为eee的任何元素。

Keep in mind that scripts are evaluated in the order they are listed in an HTML document, so your script gets run while the browser is processing the "head" section. Since the browser hasn't yet parsed the "body" section it doesn't know about any element with id "eee".

但是,通过为window.onload事件,您可以延迟执行内部HTML分配,直到窗口完全加载所有资源并安全地操作文档。

However, by assigning a function to the "window.onload" event, you can delay the execution of your inner HTML assignment until the window has completely loaded all of the resources and safely manipulate the document.

注意如果你的脚本在body部分,在列出id为eee的元素之后,那么脚本就可以工作,而不需要等待窗口load事件。

Note that if your script was in the body section, after the element with id "eee" was listed, then the script would work without the need to wait for the window "load" event.

这篇关于在html头部的javascript,innerhtml无法正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆