document.getElementById().textContent不使用变量

Qwe*_*tie 4 html javascript dom

当我使用document.getElementById().textContent将"文本内容"设置为变量的值时,它不起作用,它不会改变任何内容,而是将文本内容更改为变量的值.它在我使用时确实有效

.textContent = "example";
Run Code Online (Sandbox Code Playgroud)

但不是

.textContent = example;
Run Code Online (Sandbox Code Playgroud)

这是我的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>
Run Code Online (Sandbox Code Playgroud)

这是我的JS

//Get users name
var name = prompt("What is you name");
//put the name in the element "text space"
document.getElementById("TextSpace").textContent = name;
Run Code Online (Sandbox Code Playgroud)

出现提示,但之后没有任何反应

ade*_*neo 5

移动脚本

<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>
Run Code Online (Sandbox Code Playgroud)

或者添加一个onload处理程序

window.onload = function() {
    var name = prompt("What is you name");
    document.getElementById("TextSpace").textContent = name;
}
Run Code Online (Sandbox Code Playgroud)

现在,脚本在DOM中的元素可用之前运行.
请注意,textContentIE8及以下版本不提供此功能.