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

80
Views
Problemas con el generador de imágenes. como elimino la imagen anterior

Necesito ayuda con mi proyecto. Soy nuevo en la codificación pero estoy aprendiendo muy rápido. Tengo un generador de imágenes aleatorias, pero cada vez que hago clic en el botón quiero que las imágenes generadas anteriormente se reemplacen por las nuevas. en este momento, el generador solo agrega dos imágenes más cada vez que hago clic en el botón. Mi objetivo es que cada vez que haga clic en el botón aparezcan dos nuevas imágenes aleatorias que tomen el lugar de las dos anteriores. ¡Gracias por la ayuda! aquí está mi código a continuación, pero he redactado las imágenes porque deseo mantenerlas en privado por ahora. Puse los cachorros originales en lugar de las imágenes reales.

 document.getElementById('button').onclick = function () { //declare an array to store the images var randomImage = []; //insert the URL of images in array randomImage[0] = `https://wi.wallpapertip.com/wsimgs/15-155208_desktop-puppy-wallpaper-hd.jpg`; randomImage[1] = `http://www.petsworld.in/blog/wp-content/uploads/2014/09/running-cute-puppies.jpg`; randomImage[2] = `https://wi.wallpapertip.com/wsimgs/156-1564365_golden-retriever-puppy-desktop-wallpaper-desktop-wallpaper-puppy.jpg`; randomImage[3] = `https://wi.wallpapertip.com/wsimgs/156-1564140_free-puppy-wallpapers-for-computer-wallpaper-cave-cute.jpg`; randomImage[4] = `https://wi.wallpapertip.com/wsimgs/156-1565522_puppies-desktop-wallpaper-desktop-background-puppies.jpg`; randomImage[5] = `https://wi.wallpapertip.com/wsimgs/156-1566650_cute-puppies-desktop-wallpaper-cute-puppies.jpg`; //loop to display five randomly chosen images at once for (let i=0; i< 5; i++) { //generate a number and provide to the image to generate randomly var number = Math.floor(Math.random()*randomImage.length); //print the images generated by a random number document.getElementById("result").innerHTML += `<img src="`+randomImage[number] +`" style="width:150px" />`; } }
 <html> <head> <title> Random Image Generator </title> </head> <body> <center><h2 style="color:green"> Random Image Generator </h2></center> <h4> Click the button to generate and display the five random images: </h4> <!-- call user-defined getRandomImage function to generate image --> <button id="button">Generate Image</button> <br> <br> <span id="result" align="center"> </span> </body> </html>

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

0

Para borrar las imágenes antes de generar un nuevo conjunto, debe borrar el elemento de intervalo de result . Además, ajusté el código a continuación para declarar las imágenes en la matriz y creé una referencia al elemento fuera de la función para minimizar las tareas que se realizan en la función.

 //declare an array to store the images var randomImage = new Array(5); var imageHolder = document.getElementById("result"); //insert the URL of images in array randomImage[0] = "https://wi.wallpapertip.com/wsimgs/15-155208_desktop-puppy-wallpaper-hd.jpg"; randomImage[1] = "http://www.petsworld.in/blog/wp-content/uploads/2014/09/running-cute-puppies.jpg"; randomImage[2] = "https://wi.wallpapertip.com/wsimgs/156-1564365_golden-retriever-puppy-desktop-wallpaper-desktop-wallpaper-puppy.jpg"; randomImage[3] = "https://wi.wallpapertip.com/wsimgs/156-1564140_free-puppy-wallpapers-for-computer-wallpaper-cave-cute.jpg"; randomImage[4] = "https://wi.wallpapertip.com/wsimgs/156-1565522_puppies-desktop-wallpaper-desktop-background-puppies.jpg"; randomImage[5] = "https://wi.wallpapertip.com/wsimgs/156-1566650_cute-puppies-desktop-wallpaper-cute-puppies.jpg"; function getRandomImage() { // Clear the imageHolder innerHTML first imageHolder.innerHTML = ""; //loop to display five randomly chosen images at once for (let i = 0; i < 5; i++) { //generate a number and provide to the image to generate randomly var number = Math.floor(Math.random() * randomImage.length); //print the images generated by a random number imageHolder.innerHTML += '<img src="' + randomImage[number] + '" style = "width:150px" / > '; } }
 <center> <h2 style="color:green"> Random Image Generator </h2> </center> <h4> Click the button to generate and display the five random images: </h4> <!-- call user-defined getRandomImage function to generate image --> <button onclick="getRandomImage()"> Generate Image </button> <br> <br> <span id="result" align="center"> </span>

about 4 years ago · Juan Pablo Isaza Report

0

Como @phentnil describe en la respuesta. Lo que realmente debe hacer es limpiar sus elementos antes de generar los siguientes nuevos.

 imageHoder.innerHTML = ""

Además, tenga en cuenta que innerHTML será uno de los principales problemas de seguridad si no previene o verifica cualquier script inyectado en su interior.

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!