【发布时间】:2020-10-13 19:25:23
【问题描述】:
游戏正在运行,但是每次做出新选择时,我都会尝试用新结果替换旧结果。结果一直在堆积,直到我重新加载页面。我尝试过 if/else 语句,厌倦了添加新函数来替换旧结果,并尝试添加新事件侦听器来替换旧结果。我对此很陌生,任何建议都会很棒。谢谢。
\\
const player = {
currentChoice: null
}
const computer = {
currentChoice: null
}
const choice = ["Rock", "Paper", "Scissors"];
const rock_div = document.getElementById('r');
const paper_div = document.getElementById('p');
const scissors_div = document.getElementById('s');
rock_div.addEventListener('click', function() {
pick(choice[0]);
})
paper_div.addEventListener('click', function() {
pick(choice[1]);
})
scissors_div.addEventListener('click', function() {
pick(choice[2]);
})
function pick(userChoice) {
player.currentChoice = userChoice;
compareChoices();
console.log(player.currentChoice);
}
function computerChooses(){
const randomIndex = Math.floor(Math.random() * choice.length);
computer.currentChoice = choice[randomIndex];
}
function compareChoices(){
computerChooses();
if (computer.currentChoice === player.currentChoice){
displayResult("It's a tie! Computer and Player choose " + computer.currentChoice);
}else if(computer.currentChoice === choice[0]){
if(player.currentChoice === choice[1]){
displayResult("Player Wins! The computer chose " + computer.currentChoice + " and player
chose " + player.currentChoice);
}else{
displayResult("Computer Wins! The computer chose " + computer.currentChoice + " and
player chose " + player.currentChoice);
}
}else if(computer.currentChoice === choice[1]){
if(player.currentChoice === choice[2]){
displayResult("Player Wins! The computer chose " + computer.currentChoice + " and
player chose " + player.currentChoice);
}else{
displayResult("Computer Wins! The computer chose " + computer.currentChoice + " and player
chose " + player.currentChoice);
}
}else if(computer.currentChoice === choice[2]){
if(player.currentChoice === choice[0]){
displayResult("Player Wins! The computer chose " + computer.currentChoice + " and player
chose " + player.currentChoice);
}else{
displayResult("Computer Wins! The computer chose " + computer.currentChoice + " and
player chose " + player.currentChoice);
}
}
}
function displayResult(winner){
const result = document.createElement('h3');
result.innerText = winner;
document.body.appendChild(result);
}
\\
【问题讨论】:
-
你可以给你的 h3 一个 ID,然后每次调用 displayResult 删除具有该 ID 的元素,然后再添加新元素。
标签: javascript node.js dom