2017-01-07 42 views
1

以下是完整的错误消息:的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> 
+0

问题在于'document.write'覆盖了整个页面的内容,因此在达到该语句时不会有'#display'元素。另外'x == 1 || 2'应该是'x == 1 || x == 2'。 – Xufox

+0

相关:http://stackoverflow.com/q/12471249/4642212 – Xufox

回答

1

不要使用document.write,这是bad practice。它用test1或一些类似的字符串覆盖整个页面。因此,当达到document.getElementById("display").innerHTML = x;时,将不再存在ID为display的元素,并且document.getElementById("display")将评估为null

如果要测试if语句,请改为使用console.log("test1");。只需在大多数浏览器中打开browser consoleF12),您就会在那里看到消息。

说到你的if报表:they’re wrongif(test == 1 || 2)将始终评估为true,因为2是truthy。这不是你想要的。你想要的是if(test == 1 || test == 2)

替代品:if([1, 2].includes(test)),if([1, 2].indexOf(test) >= 0)Check variable equality against a list of values)。

相关问题