在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.