简体   繁体   English

如何将相同的事件侦听器切换为两个不同的功能?

[英]How can I toggle same Event listener to Two different function?

I am making one game which can be played by two players so if one player finish with his turn same event listener should attach to the player tow but it's not toggling between two players.我正在制作一款可供两名玩家玩的游戏,因此如果一名玩家完成了他的回合,则相同的事件侦听器应该附加到玩家拖曳上,但不会在两名玩家之间切换。

In my code I made one variable 'changeTurn' which stores the boolean value of the player turns if true then player one turn and if false player two turn.在我的代码中,我创建了一个变量“changeTurn”,它存储玩家回合的布尔值,如果为真,则为玩家一回合,如果为假,则为玩家二回合。 but in if condition changeTurn value is false still it executes the 'If(changeTurn === true)' which should not execute.但是在如果条件 changeTurn 值为 false 时,它​​仍然执行不应执行的 'If(changeTurn === true)'。 can someone help me with that please why it do like that?有人可以帮我解决这个问题,为什么会这样?

GAME RULES:

- The game has 2 players, playing in rounds
- In each turn, a player rolls a dice as many times as he whishes. Each 
  result get added to his ROUND score
- BUT, if the player rolls a 1, all his ROUND score gets lost. After that, 
  it's the next player's turn
- The player can choose to 'Hold', which means that his ROUND score gets 
  added to his GLBAL score. After that, it's the next player's turn
- The first player to reach 100 points on GLOBAL score wins the game.

 */ const rollDice = document.querySelector('.btn-roll'); const diceImage = document.querySelector('.dice'); const hold = document.querySelector('.btn-hold'); const newGame = document.querySelector('.btn-new'); let changeTurn = true; let randomNumber = 0; let loop = true; let totalScore = 0; document.querySelector('#score-0').textContent = totalScore; document.querySelector('#score-1').textContent = totalScore; let currentScore = 0; document.querySelector('#current-0').textContent = currentScore; document.querySelector('#current-1').textContent = currentScore; //while(loop){ //newGame.addEventListener('click',function(){ // loop = false; //}) if(changeTurn){ rollDice.addEventListener('click',function(){ randomNumber = Math.floor((Math.random()*6)+1); for(i = 1; i <=6 ; i++){ // selecting image by changing src name console.log(randomNumber); if(randomNumber === i ){ diceImage.setAttribute('src',`dice-${i}.png`); break; } } currentScore += randomNumber; document.querySelector('#current-0').textContent = currentScore; // adding current score to player-1 if(randomNumber === 1){ document.querySelector('#current-0').textContent = 0; //reseting player-1 current score cotent to 0 currentScore = 0; //reseting current score variable to 0 changeTurn = false; } }) hold.addEventListener('click',function(){ totalScore += currentScore; // adding total score to toatal variable document.querySelector('#score-0').textContent = totalScore; // adding total to score content document.querySelector('#current-0').textContent = 0; // reseting current score content to 0 currentScore = 0; // resetting current score variable changeTurn = false; //changning turn }) } //============================================================================ if(!changeTurn){ rollDice.addEventListener('click',function(){ randomNumber = Math.floor((Math.random()*6)+1); for(i = 1; i <=6 ; i++){ // selecting image by changing src name console.log(randomNumber); if(randomNumber === i ){ diceImage.setAttribute('src',`dice-${i}.png`); break; } } currentScore += randomNumber; document.querySelector('#current-1').textContent = currentScore; if(randomNumber === 1){ document.querySelector('#current-1').textContent = 0; currentScore = 0; changeTurn = true; } }) hold.addEventListener('click',function(){ console.log('hi') totalScore += currentScore; document.querySelector('#score-1').textContent = totalScore; document.querySelector('#current-1').textContent = 0; currentScore = 0; changeTurn = true; }) }

The problem is that you have a check during setting the event listener, but the callback of the event listener is not making any checks, hence both the events are triggered.问题是您在设置事件侦听器期间进行了检查,但是事件侦听器的回调没有进行任何检查,因此两个事件都被触发。 You could change it to:您可以将其更改为:

rollDice.addEventListener('click',function(){
  randomNumber = Math.floor((Math.random()*6)+1);

  for(i = 1; i <=6 ; i++){            // selecting image by changing src name
    console.log(randomNumber);
    if(randomNumber === i ){
      diceImage.setAttribute('src',`dice-${i}.png`);
      break;
    }
  }
  var id = changeTurn? 0: 1;
  currentScore += randomNumber;
  document.querySelector(`#current-${id}`).textContent = currentScore; // adding current score to player-1

  if(randomNumber === 1){
    document.querySelector(`#current-${id}`).textContent = 0;  //reseting player-1 current score content to 0
    currentScore = 0;                                      //reseting current score variable to 0
    changeTurn = !changeTurn;
  }

})

hold.addEventListener('click',function(){
  var id = changeTurn? 0: 1;
  totalScore += currentScore;                                  // adding total score to total variable
  document.querySelector(`#score-${id}`).textContent = totalScore; // adding total to score content
  document.querySelector(`#current-${id}`).textContent = 0;        // reseting current score content to 0
  currentScore = 0;      // resetting current score variable
  changeTurn = !changeTurn;   //changing turn
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何创建一个单一的 function 将由事件侦听器调用,而不是为每个不同的按钮调用 function? - How can I create ONE single function that will be called by an event listener instead of function for each different button? 如何在两个不同的脚本中使用相同的 JS function? - How can I use the same JS function in two different scripts? 如何在初始化函数中将原型函数添加到事件侦听器? - How can I add a prototype function to an event listener in the initialization function? 如何在具有事件侦听器的 div 的两个背景图像之间切换 - How to toggle between two background images for a div having an event listener 如何通过事件侦听器将按键值传递给 function? - How can I pass a keypress value to a function, through an event listener? 如何禁用事件监听器? 或具有停止按钮的功能? - How can i disable the event listener? or having a stop button for it function? 如何将事件监听器添加到函数表达式 - How can I add Event Listener to a function expression 添加事件侦听器时如何将数据传递给函数? - How can I pass data to a function when adding an event listener? 如何在 function 中等待事件侦听器? - How can I await an event listener inside a function? 如何使用 php 和 ajax 从同一个切换开关触发两个不同的事件 - how to fire two different event from the same toggle switch using php and ajax
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM