我想在游戏中添加一些图片。当您单击按钮时,它应该会出现一个图像。有些人请告诉我或告诉我该怎么做?
我的HTML:
<div style="text-align: center;">
<H1>Rock Paper Scissors</H1>
<H2>Instructions</H2>
<p>Click a button to choose what to throw</p>
<p id="buttons">
<input type="button" value="Rock" onclick="hand(0);" />
<input type="button" value="Paper" onclick="hand(1);" />
<input type="button" value="Scissors" onclick="hand(2);" />
</p>
<h3>Scoreboard:</h3>
<ul id="scoreboard">
Wins: <span id="win">0</span>
<br/>
Losses: <span id="lose">0</span>
<br/>
Ties: <span id="tie">0</span>
</ul>
我的JavaScript:
var ties = 0;
var wins = 0;
var losses = 0;
// randInt returns a random integer between 0 and 2
function randInt() {return Math.floor(Math.random()*3);}
function msgAlert(msg, player, comp) {
var outcome = ["Rock", "Paper", "Scissors"];
if (msg === "tie") {
alert("Tie!\n" + "Player: " + outcome[player] + "\n" + "Computer: " + outcome[comp]);
}
if (msg === "win") {
alert("You won!\n" + "Player: " + outcome[player] + "\n" + "Computer: " + outcome[comp]);
}
if (msg === "lose") {
alert("You lost!\n" + "Player: " + outcome[player] + "\n" + "Computer: " + outcome[comp]);
}
}
function updateScore(result) {
var tie = document.getElementById("tie");
var win = document.getElementById("win");
var lose = document.getElementById("lose");
if (result === "tie") {
ties++;
tie.innerHTML = ties;
}
if (result === "win") {
wins++;
win.innerHTML = wins;
}
if (result === "lose") {
losses++;
lose.innerHTML = losses;
}
}
function hand(player) {
var comp = randInt();
if (player === comp) {
updateScore("tie");
msgAlert("tie", player, comp);
}
/* Rock Conditions */
if (player === 0 && comp === 1) {
updateScore("lose");
msgAlert("lose", player, comp);
}
if (player === 0 && comp === 2) {
updateScore("win");
msgAlert("win", player, comp);
}
/* Paper Conditions */
if (player === 1 && comp === 0) {
updateScore("win");
msgAlert("win", player, comp);
}
if (player === 1 && comp === 2) {
updateScore("lose");
msgAlert("lose", player, comp);
}
/* Scissors Conditions */
if (player === 2 && comp === 0) {
updateScore("lose");
msgAlert("lose", player, comp);
}
if (player === 2 && comp === 1) {
updateScore("win");
msgAlert("win", player, comp);
}
}
答案 0 :(得分:1)
您可以使用getElementByClass和onClick来设置侦听器函数。 类似的东西:
getElementByClass('.button').onClick = function(){
}
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.onclick
然后在匿名函数中,您可以编写一些代码,使图像显示在您想要的位置。你可以使用像.appendChild
这样的东西https://developer.mozilla.org/en-US/docs/Web/API/Node.appendChild
上面发布的.appendChild链接中有一个很好的例子。希望它有所帮助。
编辑:你也可以调查一下jQuery,一旦你感觉到它就可以让这种DOM操作更容易。