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

183
Views
Estoy tratando de agregar un evento de clic a mi imagen sin éxito en Javascript

Tengo una serie de imágenes que se muestran al hacer clic en el botón en orden aleatorio. He confirmado que se puede hacer clic en todas las imágenes y que muestran la fuente de imagen correcta en la consola. Lo que no puedo hacer es crear un evento de clic que avise un mensaje cuando se hace clic en una imagen. Cuando hago clic en la imagen "A1", se muestra la alerta "No", así que supongo que el problema puede ser que la cadena de la imagen y la imagen real no están vinculadas entre sí.

 const images$front = [ { name: "A1", img: "A1.png" }, { name: "B1", img: "B1.png", }, { name: "A2", img: "A2.png", }, { name: "B2", img: "B2.png", }, { name: "A3", img: "A3.png", }, { name: "B3", img: "B3.png", }, { name: "A4", img: "A4.png", }, { name: "B4", img: "B4.png", }, ]; //Rear image const images$rear=[ { name: "z", img: "z.png" , }, ]; function shuffle(array) { let currentIndex = array.length, randomIndex; while (currentIndex != 0) { randomIndex = Math.floor(Math.random() * currentIndex); currentIndex--; [array[currentIndex], array[randomIndex]] = [ array[randomIndex], array[currentIndex] ]; } } shuffle(images$front) function DisplayImage(i) { let CardImage = document.createElement('img'); CardImage.src = `Images/${images$front[i].img}` CardImage.alt = CardImage.src; document.querySelector("#box").appendChild(CardImage); CardImage.addEventListener("click", function(e) { if (CardImage === "A1") { alert("Yes") } else { alert("No") } console.log(e.target.src) }) }

Gracias

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

0

Su condición está tratando de igualar entre el objeto y la cadena, CardImage es HTMLImageElement, que siempre será falso, puede agregar otra propiedad "nombre" y luego establecer la condición.

 function DisplayImage(i) { let CardImage = document.createElement('img'); CardImage.src = `Images/${images$front[i].img}` CardImage.alt = CardImage.src; CardImage.name = images$front[i].name; //here is the change. document.querySelector("#box").appendChild(CardImage); CardImage.addEventListener("click", function(e) { if (CardImage.name === "A1") { //change here too. alert("Yes") } else { alert("No") } console.log(e.target.src) }) }
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!