Javascript:不改变 div innerHTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10157983/
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: Does not change the div innerHTML
提问by Ali
I really cannot understand why this does not work. I've tried couple of tricks but I just don't get it.
我真的不明白为什么这不起作用。我已经尝试了几个技巧,但我就是不明白。
<html>
<head>
<script type="text/javascript">
alert('Hey');
var vText = document.getElementById("results");
vText.innerHTML = 'Changed';
alert(vText.innerHTML);
</script>
</head>
<body>
<div id="results">
hey there
</div>
</body>
</html>
回答by Nobita
This is working as you can see here:
正如您在此处看到的那样,这是有效的:
It's important that you put the JavaScript after your HTML div container.
将 JavaScript 放在 HTML div 容器之后很重要。
回答by David says reinstate Monica
The problem that you're facing is that the browser runs the JavaScript as it's encountered when rendering/processing the page. At this point it will alert()
your message, but the relevant element, the #results
div
isn't present in the DOM, so nothing can be changed.
您面临的问题是浏览器在呈现/处理页面时运行 JavaScript。此时它会显示alert()
您的消息,但相关元素#results
div
不存在于 DOM 中,因此无法更改任何内容。
To address this, you can either place the script
at the end of the page, just before the closing </body>
tag, or run the code in the onload
event of the body
or window
.
为了解决这个问题,你可以放置script
在页面的结束,在结束之前</body>
的标签,或运行中的代码onload
的事件body
或window
。
回答by Dr.Molle
The script has to be placed after the div#results or executed onload, otherwise the element is still unknown when you try to access it.
脚本必须放在 div#results 之后或在加载时执行,否则当您尝试访问该元素时仍然未知。
回答by Nazmul
You need to call this script in onload event i.e
您需要在 onload 事件中调用此脚本,即
window.onload=function(){
//your code
}
回答by iDroid
<html>
<head>
<script type="text/javascript">
function onloadCall()
{
alert('Hey');
var vText = document.getElementById("results");
vText.innerHTML = 'Changed';
alert(vText.innerHTML);
}
</script>
</head>
<body onload="onloadCall()">
<div id="results">
hey there
</div>
</body>
</html>
Hope the above snippet shows you the fix
希望上面的代码片段向您展示了修复方法