以下是完整的错误消息:的document.getElementById到document.write后,现有的元素返回null
mlg.html:41 Uncaught TypeError: Cannot set property 'innerHTML' of null
at ml (mlg.html:41)
at HTMLButtonElement.onclick (mlg.html:9)
我是在填字游戏,我只是做了一个快速测试,以发现问题和然后我偶然发现了这个问题。下面是代码:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button type="button" onclick="ml()">Mad Libs!</button>
<p id="display"></p>
<script>
function ml() {
var x = Math.floor((Math.random() * 10) + 1);
//mad lib 1
if (x == 1 || 2) {
document.write("test1");
}
//mad lib 2
if (x == 3 || 4) {
document.write("test2");
}
//mad lib 3
if (x == 5 || 6) {
document.write("test3");
}
//mad lib 4
if (x == 7 || 8) {
document.write("test4");
}
//mad lib 5
if (x == 9 || 10) {
document.write("test5");
}
document.getElementById("display").innerHTML = x;
}
</script>
</body>
</html>
问题在于'document.write'覆盖了整个页面的内容,因此在达到该语句时不会有'#display'元素。另外'x == 1 || 2'应该是'x == 1 || x == 2'。 – Xufox
相关:http://stackoverflow.com/q/12471249/4642212 – Xufox