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

238
Views
¿Cómo tener la identificación de datos de un elemento cuando hace clic en él?

Creo varios botones y les doy una identificación en un bucle y me gustaría que cuando hagamos clic en él, su identificación se muestre en la consola. Esto es lo que traté de hacer, pero el programa devuelve la última identificación asignada después del ciclo.

 for (var i = 0; i < 3; i++) { var button = document.createElement('button'); button.textContent = "Add to cart"; button.setAttribute("data-id", i+1); card.appendChild(button); button.onclick = function() { let attribut = button.getAttribute("data-id"); console.log(attribut) };

}

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

0

Cuando se llama al onclick , el button todavía está configurado en el último botón en su ciclo; no hay referencia al button en su onclick . En su lugar, intente pasar el evento ( e ) al onclick , luego haga referencia al objetivo del evento con e.target .

 for (var i = 0; i < 3; i++) { var button = document.createElement('button'); button.textContent = "Add to cart"; button.setAttribute("data-id", i+1); document.body.appendChild(button); button.onclick = function(e) { let attribut = e.target.getAttribute("data-id"); console.log(attribut) }; }

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!