Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

210
Vistas
bucle aleatorio con jquery en datos Json usando forEach

Tengo este código que muestra todas las imágenes que están en un archivo json. ¿Alguna forma de mostrar solo 1 imagen y aleatoriamente con las del .json?

tengo este codigo:

 $(document).ready(function() { $.getJSON('https://res.cloudinary.com/dkx20emez/image/list/dom.json', function(emp) { //the attribute resource is an array so you have to loop each element in it emp.resources.forEach(function(element){ var publicid = element.public_id; var format = element.format; var type = element.type; var version = element.version; $('#display').append('<img class="wrapper" src="https://res.cloudinary.com/dkx20emez/image/'+ type +'/v'+version +'/'+publicid+'.'+format +'">'); }); }); });
 **css** body { padding: 50px; } .wrapper { width: 200px; height: auto; padding: 10px; background: #eee; } .random-faces { width: 100%; max-width: 200px; height: 0; padding-bottom: 100%; background-repeat: no-repeat; background-position: center center; background-size: cover; }
 //css <html><head> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script></head> <body> <div class="wrapper" id="display" style="background-color:#39B54A;"></div> </body> </html>

les agradezco sus respuestas

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Simplemente puede generar un número entero aleatorio entre 0 y la longitud de la matriz devuelta -1. He incluido un método fácil que realiza esto desde esta publicación:

Generar número aleatorio entre dos números en JavaScript

Luego, puede usar ese número entero aleatorio como índice de emp.resources para obtener una imagen aleatoria.

Vea el fragmento a continuación:

(Olvidé la mayor parte del jQuery que una vez conocí, por lo que hay Vanilla JS mezclado)

 // Custom function to get a random integer between two numbers const randomIntFromInterval = (min, max) => Math.floor(Math.random() * (max - min + 1) + min); $(document).ready(function() { $.getJSON('https://res.cloudinary.com/dkx20emez/image/list/dom.json', function(emp) { //Get a random number between 0 and the length of the emp.resources array - 1 var index = randomIntFromInterval(0, emp.resources.length - 1) // Then just use that random number as the index of the array var element = emp.resources[index] var publicid = element.public_id; var format = element.format; var type = element.type; var version = element.version; //Create an img element const img = document.createElement(`img`); //Add in the class to the img img.classList.add(`wrapper`); //Add in the source to the img img.src = `https://res.cloudinary.com/dkx20emez/image/${type}/v${version}/${publicid}.${format}`; $('#display').append(img); }); });
 body { padding: 5px; } .wrapper { width: 200px; height: auto; padding: 10px; background: #eee; } .random-faces { width: 100%; max-width: 200px; height: 0; padding-bottom: 100%; background-repeat: no-repeat; background-position: center center; background-size: cover; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="wrapper" id="display" style="background-color:#39B54A;"></div>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda