2016-07-30 90 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功能