代码的Javascript问题,TypeError:comp1GameTitle为null

时间:2016-07-30 10:08:35

标签: javascript jquery

再次欢迎,再次欢迎。我有很多错误,它只是和我开玩笑。 代码在这里工作=> https://jsfiddle.net/jh5tkfpp/由论坛成员(Sridhar)发布。但是在我的本地网络服务器中它正在抛出TypeError: comp1GameTitle is 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>
	<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
	<meta content="utf-8" http-equiv="encoding">
        <title>Random_page</title>
        <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
	<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>

1 个答案:

答案 0 :(得分:0)

它在jsfiddle中工作,因为它们被执行onload。但是您已将脚本放在head中。所以当它们被执行时,DOM还没有准备就绪,没有id为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保留在标头标记内,但将所有代码放在window.onload函数中的rnd.js中