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

491
Views
¿Cómo recuperar el eventListener después de replaceChild en vanila javascript?

Bueno, quiero preguntar algo sobre replaceChild aquí y tuve problemas cuando usé esa función, por lo que el problema es cuando tengo alguna función addEventListener en mi botón, cuando reemplacé el botón anterior por un elemento nuevo y luego lo traigo de nuevo, mi El detector de eventos en mi botón anterior no funciona como antes, ¿alguna sugerencia para mantener mi detector de eventos funcionando en mi botón cuando se reemplazó? Oh, a continuación les daré todos los enlaces de ejemplo de mi problema, pueden acceder para comprender más sobre mi problema, ¡gracias antes que tengan un buen día!

Voy a poner mi código a continuación:

 const button = document.querySelectorAll('.button'); button.forEach(function (element) { element.addEventListener('click', function () { const buttonClass = element.classList; if (buttonClass.contains('custom')) { const buttons = document.querySelector('.buttons'); const testElement = document.createElement('p'); testElement.innerHTML = "I'm Paragraph" buttons.replaceChild(testElement, buttons.lastElementChild); } else { const buttons = document.querySelector('.buttons'); const customElement = document.createElement('button'); customElement.className = "button custom" customElement.innerHTML = "5" buttons.replaceChild(customElement, buttons.lastElementChild); } }); }); document.querySelector('.custom').addEventListener('click', function () { console.log('you touched me!') });
 <div class="buttons"> <button class="button">1</button> <button class="button">2</button> <button class="button">3</button> <button class="button">4</button> <button class="button custom">5</button> </div>

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

0

Utilice la delegación de eventos: escuche el clic en un elemento contenedor. Estos eventos de clic aumentan, por lo que incluso cuando un nuevo botón genera el evento, aumentará hasta el contenedor que está escuchando.

Puede hacer lo mismo con los botones que no se reemplazan, por lo que su código permanece unido y no tiene que iterar los botones.

Código adaptado:

 const buttons = document.querySelector('.buttons'); // Listen on a container element -- could even be body // Grab the event argument document.querySelector('.buttons').addEventListener('click', function (e) { // Then check whether the source of the event was our button const buttonClass = e.target.classList; if (buttonClass.contains("custom")) { console.log('you touched me!'); const testElement = document.createElement('p'); testElement.innerHTML = "I'm Paragraph"; buttons.replaceChild(testElement, buttons.lastElementChild); } else { const customElement = document.createElement('button'); customElement.className = "button custom"; customElement.innerHTML = "5"; buttons.replaceChild(customElement, buttons.lastElementChild); } });
 <div class="buttons"> <button class="button">1</button> <button class="button">2</button> <button class="button">3</button> <button class="button">4</button> <button class="button custom">5</button> </div>

about 4 years ago · Juan Pablo Isaza Report

0

Cuando recupera el elemento, eso significa que está agregando el nuevo elemento al HTML DOM. En este caso, nuevamente, debe vincular ese elemento con eventListener. Sugeriría usar clases para vincular el evento y delegar o eliminarEventListner y volver a vincularlo cada vez que devuelva el elemento al DOM.

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!