当我的一个函数被称为“switchTurn”时,我正在尝试更改图像的来源但是,它不起作用,而且firebug一直在说这是因为:
TypeError: document.getElementById("turns") is null
document.getElementById('turns').src = x;
我不明白,除了带有“转弯”ID的图像之外,我能够更改所有图像的来源。有谁可以帮我解决这个问题?
HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<head>
<link rel="stylesheet" type="text/css" href="default.css" />
<script language="Javascript" src="default.js" ></script>
</head>
<body onload="DisplayPlayed()" onmousedown="return false">
<div id="wrapper" onmousedown="return false">
<div id="Bcards" onmousedown="return false">
<img src="turnedcard.png" id="Bcard01"/>
<img src="turnedcard.png" id="Bcard02"/>
<img src="turnedcard.png" id="Bcard03"/>
<img src="turnedcard.png" id="Bcard04"/>
<img src="invisiblecard.png" id="Bcard05"/>
<img src="invisiblecard.png" id="Bcard06"/>
<img src="invisiblecard.png" id="Bcard07"/>
</div>
<div id="Pcards">
<img src="turnedcard.png" id="Pcard01"/>
<img src="turnedcard.png" id="Pcard02"/>
<img src="turnedcard.png" id="Pcard03"/>
<img src="turnedcard.png" id="Pcard04"/>
<img src="invisiblecard.png" id="Pcard05"/>
<img src="invisiblecard.png" id="Pcard06"/>
<img src="invisiblecard.png" id="Pcard07"/>
</div>
<img src="turnedcard.png" id="PlayedCards" onmousedown="return false"/>
<img src="Down.png" id="turns" onmousedown="return false"/>
<img src="Down.png" id="turns" onmousedown="return false"/>
</div>
</body>
</html>
的JavaScript
var Deck = [];
generateDeck();
var Numbers = [], Drew = 0, turn = false;
generateNumber();
function generateNumber(){
do{
Numbers[Drew] = Math.floor(Math.random() * 55);
}while(Deck[Numbers[Drew]] === "|");
Drew++;
Numbers[Drew - 1] = 44;
if(Numbers[Drew - 1] === 44 || Numbers[Drew - 1] === 45 || Numbers[Drew - 1] === 46 || Numbers[Drew - 1] === 47){
switchTurn();
}
}
function generateDeck(){
for(i = 0; i < 56; i++){
Deck[i] = i.toString();
}
}
function discard(){
Deck[Numbers[Drew]] = "|";
}
function switchTurn(){
if(turn === true){
arrowTurn("Up.png");
turn = false;
}else if(turn === false){
arrowTurn("Down.png");
turn = true;
}
}
function arrowTurn(x){
document.getElementById('turns').src = x;
}
function DisplayPlayed(){
document.getElementById("PlayedCards").src = Deck[Numbers[Drew - 1]] + ".png";
discard();
}
答案 0 :(得分:5)
您的JavaScript文件包含在上方 <body>
标记中的元素。要解决此问题,请将脚本标记移动到其中元素下的正文中,或使用window.onload
或DOM-ready方法的任何变体。