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

110
Views
¿Es posible hacer que dos eventos diferentes conectados al mismo oyente se disparen en momentos diferentes?

Tengo un problema con los detectores de eventos en JS. Tengo una especie de tablero de ajedrez en mi pantalla (es decir, una caja que contiene 25 divisiones al cuadrado). Cuando hago clic en uno de esos divs, quiero que aparezca una 'A' en ese div. Cuando hago clic por segunda vez, quiero que aparezca una 'B'. Si tengo otro intento, quiero una 'A' otra vez, y luego una 'B', y luego una 'A'. Y así sucesivamente, hasta que mi tablero de ajedrez se llene de As y Bs.

Mi código ahora se parece a este:

 const showA = () => { chessBoard.addEventListener('click', function() { //code that makes an A show up }); } const showB = () => { chessBoard.addEventListener('click', function() { //code that makes a B show up }); }

Estas funciones funcionan correctamente si llamo solo a una de ellas:

 showA(); /*works*/ //showB();

Cuando los llamo a ambos, como se supone que mi código funciona para llenar el tablero de ajedrez con ambas letras, solo se activará el segundo evento.

 showA(); showB(); //Only Bs will show up on my chessboard!

Ya traté de poner a los oyentes en los divs individuales que construyen el tablero de ajedrez, pero produjo el mismo resultado.

Lo siento si este problema ya se ha planteado en hilos anteriores, pero no logré encontrar nada útil. ¡Gracias por adelantado!

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

0

Solo necesita un detector de eventos y una condición dentro de ese detector que intercambie el contenido de texto del cuadrado de A a B cuando se hace clic en él.

En este ejemplo, he usado la cuadrícula CSS para crear algunos cuadrados.

 // Cache the container element and add a handler to it // This allows us to use event delegation. The handler will // capture any event that "bubbles up" the DOM from its child // elements - in this case the nested divs. const container = document.querySelector('.container'); container.addEventListener('click', handler, false); function handler(e) { // Get the text content from the div that was clicked const { textContent } = e.target; // Reset the target content depending on that current content if (textContent === '' || textContent === 'B') { e.target.textContent = 'A'; } else { e.target.textContent = 'B'; } }
 .container { display: grid; grid-template-columns: 1fr 1fr; width: 100px; } .container div { font-size: 1.4rem; width: 50px; height: 50px; padding: 0.8em; background-color: #efefef; text-align: center; border: 1px solid #acacac; vertical-align: middle; line-height: 50px; } .container div:hover { cursor: pointer; background-color: #dfdfdf; }
 <div class="container"> <div></div> <div></div> <div></div> <div></div> </div>

Puede leer más sobre la delegación de eventos aquí .

about 4 years ago · Juan Pablo Isaza Report

0

Si entendí bien su pregunta, desea alternar entre A y B para cada llamada.

Esto se puede hacer simplemente con una bandera que se alterna en cada llamada, como ATurn = !ATurn;

 let ATurn = true; document.getElementById("test").addEventListener('click', (e) => { if (ATurn) { // code for A console.log("It's A's turn "); } else { // code for B console.log("It's B's turn "); } ATurn = !ATurn; // true becomes !true, which is false, or false becomes !false, which is true });
 <button type="button" id="test">Click me!</button>

about 4 years ago · Juan Pablo Isaza Report

0

Debe manejar el cambio entre A y B en un solo detector de eventos; aquí está el código:

 let turn = 'A'; chessboard.addEventListener('click', () => { if(turn === 'A') { //code that makes an A show up turn = 'B' } else if(turn === 'B') { //code that makes an B show up turn = 'A' } })
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!