当我点击按钮时,我的提示出现两次

i7uaboj4  于 2021-09-23  发布在  Java
关注(0)|答案(2)|浏览(327)

我正在做一个记忆拼图,点击每一个按钮,就会显示提示,让玩家写下那个数字。当我单击第一个框以填充正确的数字时,一切正常。但是,当我单击第二个框时,提示会出现两次,如果是我单击的第三个框,则会出现三次。我的代码怎么了?

number0 = document.getElementById('number1');
number1 = document.getElementById('number2');
number2 = document.getElementById('number3');
number3 = document.getElementById('number4');
number4 = document.getElementById('number5');
number5 = document.getElementById('number6');
number6 = document.getElementById('number7');
number7 = document.getElementById('number8');
number8 = document.getElementById('number9');

elements = []
elements.push(number0);
elements.push(number1);
elements.push(number2);
elements.push(number3);
elements.push(number4);
elements.push(number5);
elements.push(number6);
elements.push(number7);
elements.push(number8);

window.addEventListener('load', insertNumbers)

function insertNumbers() {
  var list = ['0', '1', '2', '3', '4', '5', '6', '7', '8']
  var shuffled = list.sort(() => Math.random() - 0.5)
  console.log(shuffled)

  number0.textContent = shuffled[0]
  number1.textContent = shuffled[1]
  number2.textContent = shuffled[2]
  number3.textContent = shuffled[3]
  number4.textContent = shuffled[4]
  number5.textContent = shuffled[5]
  number6.textContent = shuffled[6]
  number7.textContent = shuffled[7]
  number8.textContent = shuffled[8]

  setTimeout(function() {
    number0.textContent = '*'
    number1.textContent = '*'
    number2.textContent = '*'
    number3.textContent = '*'
    number4.textContent = '*'
    number5.textContent = '*'
    number6.textContent = '*'
    number7.textContent = '*'
    number8.textContent = '*'
    analiseNumbers()
  }, 2000)

  var spans = ['*', '*', '*', '*', '*', '*', '*', '*', '*']

  function analiseNumbers() {
    console.log(elements)

    number0.addEventListener('click', function() {
      i = number0;
      runApp()
    })
    number1.addEventListener('click', function() {
      i = number1;
      runApp()
    })
    number2.addEventListener('click', function() {
      i = number2;
      runApp()
    })
    number3.addEventListener('click', function() {
      i = number3;
      runApp()
    })
    number4.addEventListener('click', function() {
      i = number4;
      runApp()
    })
    number5.addEventListener('click', function() {
      i = number5;
      runApp()
    })
    number6.addEventListener('click', function() {
      i = number6;
      runApp()
    })
    number7.addEventListener('click', function() {
      i = number7;
      runApp()
    })
    number8.addEventListener('click', function() {
      i = number8;
      runApp()
    })

    function runApp() {
      var position = elements.indexOf(i)
      var chute = prompt('Qual número estava aqui?')
      if (chute === shuffled[position]) {
        i.textContent = chute;
        spans.push(chute)
        spans.sort().reverse().pop()
        console.log(spans)
        if (spans.indexOf('*') == -1) {
          alert('YOU WON!')
        } else {
          analiseNumbers()
        }
      }
      if (chute !== shuffled[position]) {
        alert('Erro!')
        insertNumbers()
      }
    }

  }
}

* {

  margin           : 3% 0%;
  margin-left      : -3%;
  padding          : 0%;
  box-sizing       : border-box;
  }
body {
  justify-content  : center;
  align-items      : center;
  display          : flex;
  flex-direction   : column;
  background-color : #1c1c1c;
  color            : #eaeaea;
  }
.row1 {
  display          : flex;
  flex-direction   : row;
  }
.row2 {
  display          : flex;
  flex-direction   : row;
  }
.row3 {
  display          : flex;
  flex-direction   : row;
  }
.number {
  height           : 40px;
  padding          : 10px 15px;
  border           : 2px solid #eaeaea;
  border-radius    : 12px;
  margin           : 15%;
  transition       : all 0.3s ease;
  cursor           : pointer;
  }
.number:hover {
  background-color : #eaeaea;
  color            : #1c1c1c;
}
<main>
  <div class="row1">
    <span class="number" id='number1'></span>
    <span class="number" id='number2'></span>
    <span class="number" id='number3'></span>
  </div>
  <div class="row2">
    <span class="number" id='number4'></span>
    <span class="number" id='number5'></span>
    <span class="number" id='number6'></span>
  </div>
  <div class="row3">
    <span class="number" id='number7'></span>
    <span class="number" id='number8'></span>
    <span class="number" id='number9'></span>
  </div>
</main>

无论如何,谢谢你的帮助。

5f0d552i

5f0d552i1#

每次调用insertnumbers()时,都会反复添加事件侦听器。
这就是为什么你的按钮在第二个数字上有2个监听器(因此有2个弹出窗口),在第三个数字上有3个。
等等
从InsertNumber中取出以下内容:

number0.addEventListener('click', function() {
    i = number0;
    runApp()
})

或者将它们放在条件中,使它们在第一次加载时只运行一次。

vptzau2j

vptzau2j2#

我做的,
…如果你想学一点!

const 
  gridButtons     = document.querySelector('#grid-buttons')
, pQuestion       = document.querySelector('#Question')
, pQuestionInput  = document.querySelector('#Question > input')
, pQuestionVerify = document.querySelector('#Question > button')
, pScore          = document.querySelector('#Score')
, pScoreResult    = document.querySelector('#Score > strong')
, pScoreValues    = document.querySelector('#Score > span')
, pPlayAgain      = document.querySelector('#Score > button')
, buttons         = [...gridButtons.querySelectorAll('span')]
, list            = Array.from({length:9},(_,i)=>i+1)
, score           = { win:0, lost:0 }
  ;
playNewGame() // init
pPlayAgain.onclick = playNewGame

function playNewGame() 
  {    
  pScore.className = 'noDisplay'
  for (let i = 8; i > 0; i--)  // shuffle Array
    {
    let j = Math.floor(Math.random() * (i + 1));
    [list[i], list[j]] = [list[j], list[i]]
    }
  buttons.forEach((bt,i)=>
    {
    bt.className   = ''
    bt.textContent = list[i]
    })
  setTimeout(()=>
    {
    buttons.forEach(bt=>bt.textContent = '*')
    }, 2000 )
  }
function seeScore( goodAnswer )
  {
  let notClickedcount = list.length
  if (goodAnswer) notClickedcount -= gridButtons.querySelectorAll('span.avoid-clicks').length

  pScoreResult.textContent =  goodAnswer ? 'You Won :)' : 'Erro! :/'  
  pScoreValues.textContent =  `win: ${score.win}  -- lost: ${score.lost}` 

  pScore.className    = ''
  pPlayAgain.disabled = goodAnswer && notClickedcount

  if (pPlayAgain.disabled)
    {
    setTimeout(_=>
      {
      pScore.className = 'noDisplay'
      }, 2000);
    }
  }
gridButtons.onclick = ({target}) =>
  {
  if (!target.matches('span')) return // ignore clicks elsewhere

  gridButtons.className = 'avoid-clicks'
  target.className      = 'onQuestion'
  pQuestion.className   = ''
  pQuestionInput.value  = ''
  pQuestionInput.focus()
  }
pQuestionVerify.onclick = _ =>
  {
  let btIndex = buttons.findIndex(bt=>bt.classList.contains('onQuestion'))

  gridButtons.className       = '' // 'avoid-clicks'
  buttons[btIndex].className  = '' // 'onQuestion'
  pQuestion.className         = 'noDisplay'

  let goodValue = (list[btIndex] === pQuestionInput.valueAsNumber)

  if (goodValue)
    {
    buttons[btIndex].textContent  = pQuestionInput.value
    buttons[btIndex].className    = 'avoid-clicks' // 'onQuestion'
    score.win++
    }
  else score.lost++;

  seeScore( goodValue )
  }

* {

  margin           : 0;
  padding          : 0;
  box-sizing       : border-box;
  }
body {
  background-color : #1c1c1c;
  color            : #eaeaea;
  }

# grid-buttons  {

  margin  : 7em auto 0 auto;
  width   : 16em;
  }

# grid-buttons span {

  display       : inline-block;
  height        : 3em;
  width         : 3em;
  text-align    : center;
  line-height   : 3em;
  margin        : 1em;
  border        : 2px solid #eaeaea;
  border-radius : .8em;
  transition    : all 0.3s ease;
  cursor        : pointer;
  }

# grid-buttons span:hover {

  background-color : #eaeaea;
  color            : #1c1c1c;
}
.avoid-clicks {
  pointer-events: none;
  }
.onQuestion {
  background : #052053;
  }
.noDisplay {
  display: none;
  }
p {
  margin        : 1em;
  border        : 2px solid #eaeaea;
  border-radius : .8em;
  padding       : 1.6em .8em;
  width         : 20em;
  }
p > input {
  width       : 2.4em;
  font-size   : 1.4em;
  text-align  : center;
  margin-left : .6em;
}
p button {
  margin   : .6em 1em 0 0;
  padding  : .3em .7em;
}
p#Score > button {
  float         : right;
  margin-bottom : .8em;
  }
<main id="grid-buttons">
  <span></span><span></span><span></span>
  <span></span><span></span><span></span>
  <span></span><span></span><span></span>
</main>

<p id="Question" class="noDisplay">
  Qual número estava aqui?
  <input type="number" min="1" max="9" value="0" >  
  <button>verify</button>
</p>
<p id="Score" class="noDisplay">
  <strong>Win or Lost</strong>
  <br><br>
  <span>Win or Lost</span>
  <button>Play Again ?</button>
  <br><br>
</p>

相关问题