【发布时间】:2020-03-15 10:53:45
【问题描述】:
很抱歉再次问这个问题,但我想为上下文添加更多代码。
我正在制作一个石头剪刀布游戏,并且想在按下按钮时更改 playerChoice 键。
我想为每个按钮添加一个 onclick 事件并运行一个函数来设置 playerChoice 属性,以便它引用 gameOptions 索引。
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>Lapis, Papyrus Scalpellus</h1>
<h2>Make a Choice</h2>
<button id="Lapis">Lapis</button>
<button id="Papyrus">Papyrus</button>
<button id=Scalpellus>Scalpellus</button>
<h2>Game Results</h2>
<script src="script.js"></script>
</body>
</html>
const gameOptions = ["Lapis", "Papyrus", "Scalpellus"];
const newChoice = randomChoice();
console.log(newChoice);
const humanPlayer = {
playerChoice: gameOptions[0],
};
const computerPlayer = {
playerChoice: randomChoice(),
};
document.querySelector("#Lapis").onclick = function() {
humanPlayer.playerChoice = gameOptions[0];
};
document.querySelector("#Papyrus").onclick = function() {
humanPlayer.playerChoice = gameOptions[1];
};
document.querySelector("#Scalpellus").onclick = function() {
humanPlayer.playerChoice = gameOptions[2];
};
console.log(humanPlayer);
//Random Choice
function randomChoice() {
const theChoice = gameOptions[Math.floor(Math.random() * 3)];
return theChoice;
}
//Players
function resultText(innerText){
const paragraph = document.createElement('p');
paragraph.innerText = innerText;
document.body.appendChild(paragraph);
}
//Outcomes
function fight(){
if(computerPlayer.playerChoice === humanPlayer.playerChoice){
resultText("Its a Tie!20. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);
}else if (computerPlayer.playerChoice === "Lapis"){
if(humanPlayer.playerChoice === "Papyrus"){
resultText("Human Player Wins!6. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);
}else if( humanPlayer.playerChoice === "Scalpellus"){
resultText("Computer Player Wins!5 You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);
}
}else if(computerPlayer.playerChoice === "Papyrus"){
if ( humanPlayer.playerChoice === "Lapis"){
resultText("Compter Player Wins!4. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);
}else if( humanPlayer.playerChoice === "Scalpellus"){
resultText("Human Player Wins!3. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);
}
}else if(computerPlayer.playerChoice === "Scalpellus"){
if ( humanPlayer.playerChoice === "Lapis"){
resultText("Human Player Wins!2. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);
}else if( humanPlayer.playerChoice === "Papyrus"){
resultText("Computer Player Wins!1. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);
}
}
}
fight()
【问题讨论】:
-
那么到底是什么问题?你说“我想为每个按钮添加一个 onclick 事件并运行一个函数来设置 playerChoice 属性,以便它引用 gameOptions 索引。”而你正是这样做的。
标签: javascript object onclick