2014-08-28 24 views
0

我工作的一個基本的問答遊戲的Javascript執行Javascript函數的時候,但是當我使用「遺漏的類型錯誤」從<script> HTML標籤

document.getElementById("demo").innerHTML = "text";

我收到此錯誤信息:

Uncaught TypeError: Cannot set property 'innerHTML' of null

Chrome控制檯中的

。我不知道爲什麼這不再有效,它在過去爲我工作。但是,如果我打開一個新的標籤,該函數將運行並且代碼有效。只有當我在相同的 標籤中運行該功能時。 我的代碼如下:

<!DOCTYPE html> 
<html> 
<head> 
    <title>Study Quiz</title> 
    <link rel="stylesheet" type="text/css" href="style.css" /> 
    <script> 
    function quiz() { 
    var rnd = Math.floor(Math.random() * 4); 
    document.getElementById("demo").innerHTML = rnd; 
    } 
    quiz(); //this one does not work 
    </script> 
</head> 
<body> 
<p id="qarea"><p> 
<p id="demo"></p> 
<script> 
quiz(); //this one does work 
</script> 
</body> 
</html> 

感謝, - 扎克

+1

dom在該狀態下還沒有準備好。 – 2014-08-28 18:36:49

回答

4

你忘了,包括前面ID您= 「演示」 它應該像<p id="demo">,而不是 <p="demo"></p>

秒第一次調用測驗不起作用的原因是您的文檔尚未加載。要做到這一點純JS

<body onload="myFunction()"> 
+1

或只是添加一個事件監聽器,如底部的例子。 – inoabrian 2014-09-02 17:31:44

-1

它應該是以下幾點。 你必須將id屬性添加到p標籤的地方。

<!DOCTYPE html> 
<html> 
<head> 
    <title>Study Quiz</title> 
    <link rel="stylesheet" type="text/css" href="style.css" /> 
    <script> 
     function quiz() { 
      var rnd = Math.floor(Math.random() * 4); 
      document.getElementById("demo").innerHTML = rnd; 
     } 
     quiz(); // Will not work here because there is no such 
       // element with ID "demo" at this point in the page load. 

    </script> 
</head> 
<body> 
<p id = "qarea"><p> 
<p id = "demo"></p> 
<script> 
    document.addEventListener("DOMContentLoaded", function(){ 
     quiz(); // Will work here because the DOM is loaded at this point. 
    }); 
</script> 
</body> 
</html>