Javascript javascript更改innerhtml
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2254789/
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 change innerhtml
提问by David
ok im new at javascript, but im trying to change the innerhtml of a div tag, heres my script and its not working:
好的,我是 javascript 新手,但我试图更改 div 标签的 innerhtml,这是我的脚本,但它不起作用:
<head>
<script type="text/javascript">
function var1() {
document.getElementById('test').innerHTML = 'hi';
}
window.onLoad = var1();
</script>
</head>
<body>
<div id="test">change</div>
</body>
it should work but for some reason its not, any help?
它应该工作,但由于某种原因它不是,有什么帮助吗?
回答by Aistina
Rather than assigning var1to window.onload, you're currently calling the function and storing its result. Also, this might be obvious, but var1seems like an odd name for a function. Try this:
您当前正在调用该函数并存储其结果,而不是分配var1给window.onload。此外,这可能很明显,但var1对于函数来说似乎是一个奇怪的名称。尝试这个:
function var1() {
document.getElementById('text').innerHTML = 'hi';
}
window.onload = var1;
Note the casing of onload, as well as the missing parentheses after var1.
注意 的大小写onload,以及后面缺少的括号var1。
回答by David
using .innerHTMLis non-standard,and a terrible practice for many reasons. you should create a new element using the proper standard methods and and add it to the tree where you want it
使用.innerHTML是非标准的,并且出于多种原因是一种可怕的做法。您应该使用适当的标准方法创建一个新元素,并将其添加到您想要的树中
回答by Anatoliy
correct:
正确的:
window.onload = var1;
in your example value of window.onload is undefinedbecause function var1 returns nothing (undefined). You should set onload property to function var1, not result of calling function var1()
在您的示例中 window.onload 的值是undefined因为函数 var1 不返回任何内容 ( undefined)。您应该将 onload 属性设置为函数 var1,而不是调用函数 var1() 的结果
回答by pdavis
Your example will work if you change the uppercase "L" to a lowercase "L" in "onLoad" and remove the parenthesis after var1 where you currently have window.onLoad = var1();
如果您将“onLoad”中的大写“L”更改为小写“L”并删除当前拥有window.onLoad = var1(); 的 var1之后的括号,您的示例将起作用。
回答by Tim S. Van Haren
You're getting an element with an id of "test", but there is no element with that id in your html. There is, however, one called "text".
您获得了一个 ID 为“test”的元素,但您的 html 中没有该 ID 的元素。然而,有一种叫做“文本”。
回答by johnmdonahue
Try changing onLoad to onload.
尝试将 onLoad 更改为 onload。
function var1() {
document.getElementById('test').innerHTML = 'hi';
}
window.onload = var1; // onload
回答by Ashraf Alam
Below is another simpler version
下面是另一个更简单的版本
<body>
<div id="test">change</div>
<script type="text/javascript">
document.getElementById('test').innerHTML = 'hi';
</script>
</body>

