使用javascript从图像数组中更改img标签src。骰子游戏

时间:2016-03-14 03:58:33

标签: javascript html css image

我试图用Javascript编写一个简单的骰子游戏。代码声明了一个图像数组,以及html中的2个img标签。我试图从数组的图像中更改img标签的图像。我试图在button.onclick事件上更改img.src,但是得到2个错误:1-未捕获TypeError:无法设置属性' onclick' null,第二个错误说imgArray是未定义的!你能帮我解决这个问题吗?这是我到目前为止编写的代码:



window.onload = function() {

vvar imgArray = new Array(8);
		 
imgArray[0] = new Image();
imgArray[0].src = 'images/d1.png';

imgArray[1] = new Image();
imgArray[1].src = 'images/d2.png';

imgArray[2] = new Image();
imgArray[2].src = 'images/d3.png';

imgArray[3] = new Image();
imgArray[3].src = 'images/d4.png';

imgArray[4] = new Image();
imgArray[4].src = 'images/d5.png';

imgArray[5] = new Image();
imgArray[5].src = 'images/d6.png';

imgArray[6] = new Image();
imgArray[6].src = 'images/placeholder1.png';

imgArray[7] = new Image();
imgArray[7].src = 'images/placeholder2.png';

};

var die1 = document.getElementById("die1");
var die2 = document.getElementById("die2");

 function rollDice(){
    var status = document.getElementById("status");
    var d1 = Math.floor(Math.random() * 6) + 1;
    var d2 = Math.floor(Math.random() * 6) + 1;
    var diceTotal = d1 + d2;
    die1.src = imgArray[d1-1].src;
    die2.src = imgArray[d2-1].src;
    status.innerHTML = "You rolled "+diceTotal+".";
    if(diceTotal == 7 || diceTotal == 11){
        status.innerHTML += " You Won!";
    }
	else {
		status.innerHTML = " You Lost!";
	}
}
document.getElementById("roll").onclick = rollDice;

img.dice{
	float:left;
	width:65px;
	height: 65px;
	background-repeat: no-repeat;
	padding:1px;
	font-size:24px;
	text-align:center;
	margin:5px;
	background-size: cover;
}

<!DOCTYPE html>
<html>
<head>
<style>

</style>

</head>
<body>
<img id="die1" class="dice src="images/placeholder1.png" alt="dice1">
<img id="die2" class="dice src="images/placeholder2.png" alt="dice2">
<button id="roll">Roll Dice</button>
<h2 id="status" style="clear:left;"></h2>
</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

修复javascript的第一行:

vvar imgArray = new Array(9);//error

并关闭html和it should work中的类属性值:

<img id="die1" class="dice" src="images/placeholder1.png" alt="dice1">
<img id="die2" class="dice" src="images/placeholder2.png" alt="dice2">