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

199
Views
quiero cambiar la imagen usando for loop en js sin usar jQuery

No entiendo por qué esto no funciona? por favor dime lo que me perdí en este código ** html **

 <div id="img"> <img class="images"src="images/boy1.jpg"> </div>

** js **

 var images = new Array(); images[0] = "/images/boy1.jpg"; images[1] = "/images/boy2.jpg"; images[2] = "/images/boy3.jpg"; images[3] = "/images/girl1.jpg"; images[4] = "/images/girl2.jpg"; function changeImg(){ let img = document.querySelector(".images"); for(let i=0;i<images.length;i++){ img.src = images[i] } } document.getElementById("btn").addEventListener("click",changeImg)
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

intentalo:

 var images = new Array(); images[0] = "/images/boy1.jpg"; images[1] = "/images/boy2.jpg"; images[2] = "/images/boy3.jpg"; images[3] = "/images/girl1.jpg"; images[4] = "/images/girl2.jpg"; function changeImg() { const imgBox = document.getElementById("img"); for (let i = 0; i < images.length; i++) { const img = document.createElement("img"); img.src = images[i] imgBox.appendChild(img) } } document.getElementById("btn").addEventListener("click", changeImg)
 <div id="img"></div> <button id="btn">Start</button>

about 4 years ago · Juan Pablo Isaza Report

0

Su ciclo siempre toma la última imagen y la configura como la fuente de la etiqueta img, lo que debe hacer es cambiar el índice y luego solo configurar la imagen indexada como la fuente:

 const image = document.querySelector(".images"); let currentIndex = 0; let images = new Array(); images[0] = "/images/boy1.jpg"; images[1] = "/images/boy2.jpg"; images[2] = "/images/boy3.jpg"; images[3] = "/images/girl1.jpg"; images[4] = "/images/girl2.jpg"; const length = images.length; function changeImg(){ // increment currentIndex in a circular way; after 4 comes 0 again currentIndex = ++currentIndex % length; image.src = images[currentIndex]; } document.getElementById("btn").addEventListener("click", changeImg);
about 4 years ago · Juan Pablo Isaza Report

0

Su bucle for cambia img.src cinco veces inmediatamente, por lo que el resultado final es images[4] , no ve las otras imágenes.

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!