以下是完整的错误消息:
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
,是bad practice 。它用 test1
或一些类似的字符串覆盖整个页面。因此,当到达 document.getElementById("display").innerHTML = x;
时,将不再存在 ID 为 display
的元素,并且 document.getElementById ("display")
将计算为 null
。
如果您想测试 if
语句,请使用 console.log("test1");
反而。只需打开 browser console (在大多数浏览器中按 F12),您会在那里看到消息。
说到您的 if
语句:they’re wrong 。 if(test == 1 || 2)
的计算结果始终为 true
,因为 2
为真。那不是你想要的。你想要的是 if(test == 1 || test == 2)
。
替代方案:if([1, 2].includes(test))
、if([1, 2].indexOf(test) >= 0)
( Check variable equality against a list of values)。
关于javascript - document.getElementById 在 document.write 之后的现有元素上返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41517021/