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

157
Views
eliminar eventListener del ciclo for

Estoy tratando de eliminar el detector de eventos que agregué en bucle for pero no funcionó

¿Hay alguna manera de hacer esto con js puro?

 for (let i = 0; i < drumPads.length; i++) { drumPads[i].addEventListener("click", func) function func() { display.innerHTML = music[i][0]; sound.src = music[i][1]; sound.play(); } }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Su función func debe definirse fuera del ciclo.

En su código, la función func tiene un alcance de bloque y, por lo tanto, esto no se referirá a la misma memoria cuando el usuario ingrese con la condición "encendido" y "apagado".

Puede pasar el índice y algunos datos personalizados del objetivo a la función de escucha configurando el conjunto de dataset del objetivo.

 let drumPads = document.getElementsByClassName("drum-pads"); function Power(a) { for (let i = 0; i < drumPads.length; i++) { if (a === 'on') { drumPads[i].dataset.index = i; drumPads[i].addEventListener("click", func); } else { drumPads[i].removeEventListener("click", func); } } } function func(e) { const targetIndex = e.currentTarget.dataset.index; console.log('Triggered listner', targetIndex); }
 <div> <button class="drum-pads">drum-pads 1</button> <button class="drum-pads">drum-pads 2</button> <button class="drum-pads">drum-pads 3</button> <button class="drum-pads">drum-pads 4</button> </div> <div> <button onclick="Power('on')">Toggle On</button> <button onclick="Power('off')">Toggle Off</button> </div>

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!