Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

114
Visualizações
JavaScript - For loop within a for loop triggering twice on button press

I have a series of horizontal lists within one vertical list. Each list item has an ID 'cr-id-x_y' where x is the vertical list item index and y is the horizontal list item index. I have created a for loop within a for loop to determine which list item has been targeted. The problem I'm having is the button presses seem to be firing twice (i.e. I'm seeing "Hello world" printed to the console twice on a button press). Please can someone tell me where I'm going wrong?

document.getElementById("parent-list").addEventListener("click", function (e) {
  for (let x = 0; x < 100; x++) {
    for (let i = 0; i < 30; i++) {
      if (
        e.target.closest(`#cr-id-${x}_${i}`) &&
        (e.target.nodeName == "BUTTON" ||
          e.target.parentElement.nodeName == "BUTTON")
      ) {
        console.log("Hello world");
      }
    }
  }
});
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

From the code you posted, it is not possible to guess why it is firing twice, but actually there is no need to loop at all. When you delegate like you do, you should be able to interrogate the clicked target - for example like this

document.getElementById("parent-list").addEventListener("click", function(e) {
  const tgt = e.target; // or if nested e.target.closest('button'), then use tgt in the next if
  if (tgt.tagName==="BUTTON") {
    const someParent = tgt.closest('someElementThatMightHaveCRId');
    if(someParent.id && someParent.id.startsWith('cr-id-')) {                
      console.log("Hello world",someParent.id);
    }
  }
})
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda