• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

243
Views
Quiero que no se repitan las imagenes, solo cambiar el orden aleatoriamente

Tengo este código de codepen, pero al cargar las imágenes las repite, y lo que quiero hacer es que sigan apareciendo aleatoriamente, pero no repetirlas.

HTML:

 <!DOCTYPE html> <html lang="en" > <head> <meta charset="UTF-8"> <title>CodePen - Random image grid</title> <link rel="stylesheet" href="./style.css"> </head> <body> <!-- partial:index.partial.html --> <!-- partial --> <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script><script src="./script.js"></script> </body> </html>

JS:

 document.addEventListener('DOMContentLoaded', function() { for (i=1; i<8; i++){ (function(i){ setTimeout(function () { $('<img class="sq" src="ads/ads-' + Math.floor((Math.random() * 7)+1) + '.jpg">').appendTo('body'); }, i * 1); }(i)); }; }, false);

Alguna idea de como puedo hacerlo, soy algo nuevo en js, solo estoy aprendiendo

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

0

En lugar de generar números aleatorios en cada iteración, genere la matriz de números posibles (0..7), mezcle y luego use esa matriz mezclada para producir las imágenes.

Nodo lateral: a medida que usa jQuery, utilícelo con todo su potencial:

 function shuffle(a) { for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; } $(function() { let nums = shuffle([...Array(8).keys()]); (function loop() { if (!nums.length) return; let i = nums.pop() + 1; $("<img>", { class: "sq", src: `ads/ads-${i}.jpg`, alt: i }).appendTo("body"); setTimeout(loop, 100); })(); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

about 3 years ago · Juan Pablo Isaza Report

0

Puede crear una matriz con todas las imágenes que desea agregar. Luego, mientras haya al menos una imagen, la agrega a la pantalla y la elimina de la matriz en un intervalo determinado.

 document.addEventListener( "DOMContentLoaded", function () { const imgs = []; for (let i = 1; i < 8; i++) { imgs.push(`ads/ads-${i}.jpg`); } const intervalID = setInterval(() => { while (imgs.length > 0) { const img = imgs[Math.floor(Math.random() * imgs.length)]; $( `<img class="sq" src="${img}">` ).appendTo("body"); imgs.splice(imgs.indexOf(img), 1); } clearInterval(intervalID); }, 100); }, false );
about 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error