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

470
Views
¿Cómo puedo renderizar imágenes con JavaScript en mi HTML?

Quiero renderizar imágenes con JavaScript en mi archivo HTML. No puedo encontrar el problema, aquí está mi código de JavaScript y HTML. Realmente aprecio cuando alguien me puede ayudar.

¡Que tú!

 const imgs = [ "images/p1.jpg", "images/p2.jpg", "images/p3.jpg" ] const container = document.getElementById("container") function renderImages() { let getImgs = "" for (let i = 0; i < imgs.length; i++) { getImgs = `<img scr="${imgs[i]}">` } container.innerHTML = getImgs } renderImages() <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Headline</h1> <div id="container"> </div> <script src="index.js"></script> </body> </html>
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

El problema es que usa un signo igual ( = ) en lugar de un signo más-igual ( += ). El signo más-igual agregará el texto a la variable, mientras que el signo igual sobrescribirá la variable.

Esta línea:

 getImgs = `<img scr="${imgs[i]}">`

getImgs se establece en la cadena, la cadena no se le agrega. Necesitas cambiarlo a algo como esto:

 getImgs += `<img scr="${imgs[i]}">`

(Observe el signo más antes del signo igual)

De esta manera, la variable no se cambiará por completo, sino que se agregará.

Código completo:

 const imgs = [ "images/p1.jpg", "images/p2.jpg", "images/p3.jpg" ] const container = document.getElementById("container") function renderImages() { let getImgs = "" for (let i = 0; i < imgs.length; i++) { getImgs += `<img scr="${imgs[i]}">` } container.innerHTML = getImgs } renderImages()
 /* I added css so you can see the images */ img { border: 1px solid black; width: 20px; height: 20px; background: linear-gradient(90deg, blue, green); }
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Headline</h1> <div id="container"> </div> </body> </html>

El CSS se agregó solo para que pueda ver dónde están las imágenes.

about 4 years ago · Juan Pablo Isaza Report

0

const imgs = [ "images/p1.jpg", "images/p2.jpg", "images/p3.jpg" ]; // list of sources of images to be rendered const container = document.getElementById("container"); // the element that is going to contain those images const loadImage = url => { return new Promise((resolve, reject) => { const img = new Image(); img.onload = () => resolve(img); // resolve the promise if the image has been successfully loaded img.onerror = () => reject(); // else reject the promise img.src = url; // set the source only after the event handlers have been set }); }; const renderImages = async () => { try { const loadedImages = await Promise.all(imgs.map(loadImage)); const frag = document.createDocumentFragment(); frag.append(...loadedImages); container.appendChild(frag); } catch { console.error("Couldn't render the images"); } }; renderImages();

aquí la función loadImage se usa para cargar las imágenes y devuelve una promesa que se resuelve solo cuando se han cargado las imágenes

luego, en la función renderImages , esperamos hasta que se hayan cargado todas las imágenes, luego agregamos todas esas imágenes a un fragmento de documento para reducir la cantidad de actualizaciones de dom, y finalmente agregamos ese fragmento de documento al contenedor.

Espero que ayude y, por favor, disculpe mi mal inglés.

about 4 years ago · Juan Pablo Isaza Report

0

Con su código, el resultado es solo una etiqueta de imagen (img): resultado con su código

Debe incluir el HTML interno dentro del ciclo: InnerHTML dentro del ciclo

Y eso es todo. resultado HTML

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!