Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

438
Visualizações
¿Cómo hacer que se pueda hacer clic en imágenes aleatorias para páginas dedicadas usando javascript?

He estado tratando de arreglar esto durante días y no puedo hacer que funcione, necesito que las imágenes en mi código JavaScript tengan sus propios enlaces a otra página en mi sitio web (es decir, index1.html , index2.html , index3.html )

El usuario genera una imagen aleatoria y cuando aparece la imagen, puede hacer clic en la imagen e ir a la página específica a la que está vinculada la imagen.

¿Tiene sentido?

 function getRandomImage() { //declare an array to store the images var randomImage = new Array(); //insert the URL of images in array randomImage[1] = "frames/1.png"; //this needs to have a link randomImage[2] = "frames/2.png"; //this needs to have a link randomImage[3] = "frames/3.png"; //this needs to have a link randomImage[4] = "frames/4.png"; //this needs to have a link randomImage[5] = "frames/5.png"; //this needs to have a link randomImage[6] = "frames/6.png"; //this needs to have a link randomImage[7] = "frames/7.png"; //this needs to have a link randomImage[8] = "frames/8.png"; //this needs to have a link randomImage[9] = "frames/9.png"; //this needs to have a link randomImage[10] = "frames/10.png"; //this needs to have a link //loop to display five randomly chosen images at once for (let i = 0; i < 1; 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 += '<a href="' + randomImage[number] + '"><img src="' + randomImage[number] + '" style="width:450px" /></a>'; } }
 <button onclick="getRandomImage()">Show Image</button> <div class="container"> <span id="result" align="center"></span> </div>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

¿Intentaste usar objetos dentro de tu matriz? Daré un ejemplo:

 function getRandomImage() { //declare an array to store the images var randomImage = new Array(); //insert the URL of images in array randomImage[0] = {img: "frames/1.png", url:"index1.html"}; randomImage[1] = {img: "frames/2.png", url:"index2.html"}; randomImage[2] = {img: "frames/3.png", url:"index3.html"}; var number = Math.floor(Math.random()*randomImage.length); let a = document.createElement("a") a.href = randomImage[number].url let img = document.createElement("img") img.src = randomImage[number].img img.style.width = "450px" a.append(img) document.getElementById("result").append(a) }

Y es más limpio. Realmente no entiendo el bucle for cuando ya creaste un generador de números aleatorios.

about 4 years ago · Juan Pablo Isaza Relatório

0

Esto se puede hacer simplemente. Su idea de configurar el HTML interno es genial, pero su ejecución del ciclo for está un poco fuera de lugar. Aquí hay una demostración funcional que usa algunas imágenes aleatorias de GIHPY. También recomendaría usar una matriz de objetos para almacenar fácilmente el enlace de la imagen y la URL correspondiente.

 const button = document.getElementById('clickMe') const images = [ { img: 'https://media4.giphy.com/media/GvaFelN8tSroAESiS9/giphy.webp', url: 'https://media4.giphy.com/media/GvaFelN8tSroAESiS9/giphy.webp' }, { img: 'https://media0.giphy.com/media/hIXt83jcZWxUDhC2LD/giphy.webp', url: 'https://media0.giphy.com/media/hIXt83jcZWxUDhC2LD/giphy.webp' }, { img: 'https://media4.giphy.com/media/6pNyPn7KbMbijMEDf8/giphy.webp', url: 'https://media4.giphy.com/media/6pNyPn7KbMbijMEDf8/giphy.webp' }, { img: 'https://media1.giphy.com/media/iJaw9MBLbqpgQvhcg4/giphy.webp', url: 'https://media1.giphy.com/media/iJaw9MBLbqpgQvhcg4/giphy.webp' }, ]; function getRandomImage() { let randomImage; for (let i = 0; i < images.length; i++) { randomImage = images[Math.floor(Math.random() * images.length)]; } document.getElementById('result').innerHTML = `<a href="${randomImage.img}" target="_blank"><img src="${randomImage.url}" style="width:450px"/></a>` } button.addEventListener('click', getRandomImage);
 <button id="clickMe">Show Image</button> <div class="container"> <span id="result"></span> </div>

Además, recomendaría usar literales de plantilla en lugar de concatenar cosas usando símbolos más. Se pone un poco desordenado de esa manera))

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda