Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

288
Views
¿Cómo hacer que la identificación del botón en el que se hizo clic se use repetidamente más tarde en diferentes funciones?

Quiero almacenar lo que se está haciendo clic, para que pueda usarse varias veces en un juego de piedra, papel o tijera. Necesito usar esto hasta que el jugador o la computadora obtengan 5 puntos. ¡Cualquier sugerencia será apreciada!

archivo HTML:

 <div class = buttons> <button id="rock">Rock</button> <button id="paper">Paper</button> <button id="scissors">Scissors</button> </div>

Archivo JavaScript:

Puedo registrar el button.id, sin embargo, no es útil ya que no puedo usarlo en ninguna otra función.

 const buttons = document.querySelectorAll('button'); buttons.forEach(button => button.addEventListener('click', () => { console.log(button.id)})); //get the button.id

# Actualización 1

Traté de almacenarlo en una matriz como se indica en las respuestas,
 const buttons = document.querySelectorAll('button'); buttons.forEach(button => button.addEventListener('click', () => { const {id} = button playerChoices.push(id) handleChoice(id) }) ); const handleChoice = id => { console.log(id) console.log(playerChoices) }

Quiero usarlo en esta función: juego () pero no puedo llamar al valor de identificación, también probé playerSelection = playerChoices[playerChoices.length - 1]; para tomar el último elemento de la matriz pero falla a "indefinido" cada vez en esta función.

 function game(){ let playerScore = 0; let computerScore = 0; // playRound() // until player or computer scores 5 while (playerScore < 5 && computerScore < 5) { const playerSelection = **UNDEFINED**; const computerSelection = counterPlay(); let roundResult = playRound(playerSelection, computerSelection); console.log(playRound(playerSelection, computerSelection)); console.log("You chose: ", playerSelection, "Computer chose: " ,computerSelection); //incrementing the score: if(roundResult.search('You win') > -1){ playerScore++; } else if (roundResult.search('You loose') > -1){ computerScore++; } console.log("you : ",playerScore , "computer : " , computerScore); if(computerScore == 5){ console.log("You lost :( I won"); } else if(playerScore == 5){ console.log("I lost, you're too good. Congrats on the win!") } } }

¿Cómo almaceno la identificación en playerSelection cada vez que hago clic?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Simplemente puede almacenarlo en una matriz o pasarlo a una función

como esto

 let playerWins = 0 let computerWins = 0 const choices = ['Rock', 'Paper', 'Scissors'] const buttons = document.querySelectorAll('button'); buttons.forEach(button => button.addEventListener('click', () => { const { id } = button playMatch(id, Math.floor(Math.random() * choices.length)) })); const startGame = () => { let playerWins = 0 let computerWins = 0 } const playMatch = (playerChoice, computerChoice) => { const result = (choices.length + playerChoice - computerChoice) % choices.length let message switch (result) { case 0: message = `it's a draw` break; case 1: message = `You won ${choices[playerChoice]} beats ${choices[computerChoice]}` playerWins++; break; default: message = `You lose ${choices[computerChoice]} beats ${choices[playerChoice]}` computerWins++; } console.log(message) if (Math.max(playerWins, computerWins) === 5) { alert('game ended') } }
 <div id="buttons"> <button id="0">Rock</button> <button id="1">Paper</button> <button id="2">Scissors</button> </div> <div id="scores"></div>

about 4 years ago · Juan Pablo Isaza Report

0

var turns = []; const buttons = document.querySelectorAll('button'); buttons.forEach(button => button.addEventListener('click', (event)=>{ console.log(event.target.id); console.log(button.id); turns.push(button.id); console.log(turns); }));

le falta uno ) del bucle foreach y el button.id funcionará siempre, use la consola del navegador para verificar la sintaxis o los errores de secuencia de comandos.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!