我正在尝试使用javascript函数更改图像。我觉得这很容易,但无法让它发挥作用。我似乎无法找到我的错误。这是javascript:
function rollDice() {
rollCount = rollCount + 1;
dice1 = Math.floor(Math.random() * 6));
switch (dice1) {
case 0:
document.getElementById("dice1").src = "Photos/redpipdice1.png";
break;
case 1:
document.getElementById("dice1").src = "Photos/redpipdice2.png";
break;
case 2:
document.getElementById("dice1").src = "Photos/redpipdice3.png";
break;
case 3:
document.getElementById("dice1").src = "Photos/redpipdice4.png";
break;
case 4:
document.getElementById("dice1").src = "Photos/redpipdice5.png";
break;
case 5:
document.getElementById("dice1").src = "Photos/redpipdice6.png";
break;
}
}
它与html链接:
<div class = "dice-images inline">
<img id = "dice1" src = "Photos/redpipdice1.png" />
<p>Click dice to hold</p>
<div class = "button">
<button id = "roll-dice" type="button" onclick = "rollDice()">ROLL!</button>
</div>
答案 0 :(得分:0)
<img id="dice1" src="Photos/redpipdice1.png" />
<button id="roll-dice" type="button">ROLL!</button>
document.getElementById(`roll-dice`).addEventListener(`click`, () => {
document.getElementById(`dice1`).src = `Photos/redpipdice${getRandomInt(1, 6)}.png`;
rollCount++;
});
function getRandomInt(min, max) {
return min + Math.floor(Math.random() * (max - min + 1));
}