2016-07-30 38 views
-1

再次歡迎,再次。我有很多錯誤,只是和我開玩笑。 代碼是在這裏工作=>https://jsfiddle.net/jh5tkfpp/張貼由論壇成員(Sridhar)。但在我的本地網絡服務器扔。JavaScript代碼問題,TypeError:comp1GameTitle爲null

var cGamePic = new Array("https://c6.staticflickr.com/9/8804/28522899701_efbaa953a7_n.jpg", "https://c5.staticflickr.com/7/6003/6004770804_692aecf57c_b.jpg", "https://c5.staticflickr.com/7/6006/6004652276_87ba0278a9_b.jpg", "https://c7.staticflickr.com/7/6139/6007896022_c7ac652043_b.jpg"); 
 
var cGameName = new Array("beach", "cycle1", "cycle2", "cycle3"); 
 
var randomItemContainer1 = Math.floor(Math.random() * cGamePic.length); //container1 
 

 
var randomItemContainer2 = Math.floor(Math.random() * cGamePic.length); //container2 
 

 
var comp1GameTitle = document.querySelector("#container1 h1"); //Heading from main container 
 
var comp1GameImage = document.querySelector("#container1 img"); //Image from main container 
 

 

 
var comp2GameTitle = document.querySelector("#container2 h1"); //Heading from main container 
 
var comp2GameImage = document.querySelector("#container2 img"); //Image from main container 
 

 

 
comp1GameTitle.innerHTML = cGameName[randomItemContainer1]; 
 
comp1GameImage.src = cGamePic[randomItemContainer1]; //Random image
<!doctype html> 
 
<html> 
 
    <head> 
 
\t <meta content="text/html;charset=utf-8" http-equiv="Content-Type"> 
 
\t <meta content="utf-8" http-equiv="encoding"> 
 
     <title>Random_page</title> 
 
     <script src="http://code.jquery.com/jquery-1.10.2.js"></script> 
 
\t <script type="text/javascript" src="rnd.js"></script> 
 
    </head> 
 
    <body> 
 
     <div id="container1" style="float:left; width:40%; margin:10px;"> 
 
      <h1>Title</h1> 
 
      <img src="" width='100%' height='100%' /> 
 
     </div> 
 
     <div id="container2" style="float:left; width:40%; margin: 10px;"> 
 
      <h1>Title</h1> 
 
      <img src="" width='100%' height='100%' /> 
 
     </div> 
 
    </body> 
 
</html>

+0

我想代碼工作正常內。它會顯示innerHtml和image,正如它假設的那樣 – jonju

回答

0

因爲它們被執行的onload它工作在的jsfiddle。但是您已將腳本放入head。所以當他們被執行DOM沒有準備好時,沒有編號爲container1的元素。所以,你可以如下面的代碼片段

<body> 
//Rest of code 
<script src="http://code.jquery.com/jquery-1.10.2.js"></script> 
<script type="text/javascript" src="rnd.js"></script> 
</body> 

別人做出改變,你仍然可以保持rnd.js標題標籤內,但放在rnd.js所有代碼window.onload功能