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

162
Visualizações
Javascript creado dinámicamente Divs

Este es un código javascript simple. Estoy creando 5 divs en script y relleno un evento 'onclick' para cada uno. Sin embargo, todos me dan la identificación del último. ¿Alguna idea de por qué ocurre este comportamiento? Muchas gracias.

 <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Test Page</title> <style type="text/css"> .divImgPoint { float: left; border-radius: 50%; width: 15px; height: 15px; margin-left: 5px; margin-right: 5px; border: ridge 2px #c73756; } .divTest { position: absolute; width: 100px; height: 100px; top: 200px; left: 100px; border: 1px solid red; } </style> <script type="text/javascript"> function createNewDivs() { var divFixed = document.getElementById('divFixed'); var newDiv; for (xI = 0; xI < 5; xI++) { newDiv = document.createElement('div'); newDiv.id = "newDiv_" + xI; newDiv.className = "divImgPoint"; newDiv.onclick = () => { alert(newDiv.id + " | " + xI); } divFixed.appendChild(newDiv); } } </script> </head> <body> <div id="divFixed"> </div> </body> </html> <script type="text/javascript"> window.addEventListener('load', () => { createNewDivs(); }); </script>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Poner let newDiv; bucle interior.

Me gusta

 <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Test Page</title> <style type="text/css"> .divImgPoint { float: left; border-radius: 50%; width: 15px; height: 15px; margin-left: 5px; margin-right: 5px; border: ridge 2px #c73756; } .divTest { position: absolute; width: 100px; height: 100px; top: 200px; left: 100px; border: 1px solid red; } </style> <script type="text/javascript"> function createNewDivs() { var divFixed = document.getElementById('divFixed'); for (xI = 0; xI < 5; xI++) { let newDiv; newDiv = document.createElement('div'); newDiv.id = "newDiv_" + xI; newDiv.className = "divImgPoint"; newDiv.onclick = () => { alert(newDiv.id + " | " + xI); } divFixed.appendChild(newDiv); } } </script> </head> <body> <div id="divFixed"> </div> </body> </html> <script type="text/javascript"> window.addEventListener('load', () => { createNewDivs(); }); </script>

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