首页 > 解决方案 > 如何更改此处的值?

问题描述

我正在创建一个石头、纸、剪刀游戏。我可以在以下位置更改玩家选择player.currentChoice = choices[2];

但是,我还将选择链接到一个 HTML 按钮,一旦单击它应该将其更改player.currentChoice = choices[0];为显示 0,因为这是摇滚的选择。

如何将主更新player.currentChoice = choices[2];player.currentChoice = choices[0];?我的功能根本不起作用我知道这不是正确的方法。我基本上需要player.currentchoice外部功能来更新,以触发我的游戏的其余部分。

const player = {
  currentChoice: null
}
const computer = {
  currentChoice: null
}

const choices = ["Rock", "Paper", "Scissors"];

player.currentChoice = choices[2];

document.getElementById('rock').addEventListener('click', updateRock);

function updateRock(){
    player.currentChoice = choices[0];
}

标签: javascriptfunctiongetelementbyid

解决方案


<button id="rock">Rock</button> 
<button id="paper">Paper</button> 
<button id="scissors">Scissors</button>     
    
    const player = {
      currentChoice: null
    }
    const computer = {
      currentChoice: null
    }
    const choices = ["Rock", "Paper", "Scissors"];
    
    player.currentChoice = choices[2];
    var rockBtn = document.getElementById('rock');
    var paprBtn = document.getElementById('paper');
    var scirBtn = document.getElementById('scissors');
    
    if(rockBtn || paprBtn || scirBtn) {
        rockBtn.addEventListener('click', updateVar);
        paprBtn.addEventListener('click', updateVar);
        scirBtn.addEventListener('click', updateVar);
    }
    function updateVar(event){
        if(event.target.id == 'rock'){
            player.currentChoice = choices[0];
        } else if (event.target.id == 'paper'){
            player.currentChoice = choices[1];
        } else if (event.target.id == 'scissors'){
            player.currentChoice = choices[2];
        }
        console.log(player.currentChoice);
    }

推荐阅读