javascript document.getElementById().textContent 不适用于变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20833682/
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
document.getElementById().textContent not working with variable
提问by Qwertie
When I use document.getElementById().textContent to set the "text content" to the value of a variable it doesn't work it doesn't to anything instead changing the text content to the value of the variable. It does work when I use
当我使用 document.getElementById().textContent 将“文本内容”设置为变量的值时,它不起作用,它不会将文本内容更改为变量的值。当我使用时它确实有效
.textContent = "example";
but not
但不是
.textContent = example;
Here is my HTML
这是我的 HTML
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script language="javascript" type="text/javascript" src="testScript.js"></script>
</head>
<body>
<p class="heading">Heading</p>
<p id="TextSpace"></p>
</body>
Here is my JS
这是我的 JS
//Get users name
var name = prompt("What is you name");
//put the name in the element "text space"
document.getElementById("TextSpace").textContent = name;
The prompt appears but after that nothing happens
出现提示但之后没有任何反应
回答by adeneo
Move the script
移动脚本
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<p class="heading">Heading</p>
<p id="TextSpace"></p>
<script language="javascript" type="text/javascript" src="testScript.js"></script>
</body>
or add an onload handler
或添加一个加载处理程序
window.onload = function() {
var name = prompt("What is you name");
document.getElementById("TextSpace").textContent = name;
}
Right now the script is running before the elements in the DOM are available.
Note that textContent
is not available in IE8 and below.
现在脚本正在 DOM 中的元素可用之前运行。
请注意,textContent
在 IE8 及以下版本中不可用。