以下是完整的错误消息:
mlg.html:41 Uncaught TypeError: Cannot set property 'innerHTML' of null
at ml (mlg.html:41)
at HTMLButtonElement.onclick (mlg.html:9)
我在做一个疯狂的libs游戏,我只是做了一个快速测试来找到错误,然后我偶然发现了这个问题。这是代码:
<!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
,这是不好的做法。它用test1
或类似的字符串覆盖整个页面。因此,当达到document.getElementById("display").innerHTML = x;
时,将不再存在ID为display
的元素,并且document.getElementById("display")
将评估为null
。
如果要测试if
语句,请改用console.log("test1");
。只需打开浏览器控制台(在大多数浏览器中F12),您就会在那里看到消息。
说到你的if
声明:他们错了。if(test == 1 || 2)
将始终求值为true
,因为2
是真的。这不是你想要的。你想要的是if(test == 1 || test == 2)
。
备选方案:if([1, 2].includes(test))
、if([1, 2].indexOf(test) >= 0)
(对照值列表检查变量相等性)。