0
我有JS的基本「岩石,紙,剪刀」遊戲的代碼。它與Promt一起工作,但我希望能夠使用按鈕進行選擇。我想使用「getElementById」和「addEventListener(」click「)」。任何人都可以將我指向正確的方向嗎?JS - 岩石,紙,剪,按鈕而不是提示
HTML:
<button id ="rock"> Rock </button>
紙 剪刀
的JavaScript:
var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
} console.log("Computer: " + computerChoice);
var compare = function (choice1, choice2) {
if (choice1 === choice2) {
return "The result is a tie!";
}
else if (choice1 === "rock") {
if (choice2 === "scissors") {
return "rock wins";
}
else {
return "paper wins";
} if (choice1 === "paper") {
if (choice2 === "rock") {
return "paper wins";
}
else {
return "scissors wins";
} if (choice1 === "scissors") {
if (choice2 === "rock") {
return "rock wins";
} else if (choice2 === "paper") {
return "scissors wins";
}
}
}
}
}
compare (userChoice, computerChoice);
我明白了,謝謝你指出,我可以問一下,你將如何代表HTML的輸出而不是控制檯? – Sergi
http://www.w3schools.com/jsref/prop_html_innerhtml.asp –