[英]i've made a javascript code that randomly displays my images from an array into a photo grid but i don't want the images to repeat
Ok so i've used javascript to randomly display images in my grid using an array the problem i have is that since its grabbing a random image sometimes it grabs the same image twice.好的,所以我使用 javascript 使用数组在我的网格中随机显示图像,我遇到的问题是,由于它有时会抓取随机图像,因此它会两次抓取相同的图像。 i will post my code below but i was just looking for a solution so that once it displays an image it won't display that image again
我将在下面发布我的代码,但我只是在寻找解决方案,以便一旦显示图像就不会再次显示该图像
this is my javascript:这是我的javascript:
var random_images_array = ['atoodbranding2.png', 'thebegining.jpg', 'ella_playin_in_the_yard.png', 'project-1.png','Frontier-attachments-for-sale.png','ipfwadd-01.jpg','invites.png'];
function getRandomImage(imgAr, path) {
path = path || 'images/portfolio/'; // default path here
var num = Math.floor( Math.random() * imgAr.length );
var img = imgAr[ num ];
var imgStr = '<img src="' + path + img + '" alt = "">';
document.write(imgStr); document.close();
}
this is my html这是我的 html
<div class="container photo-container bg-3 text-center">
<div class="photos">
<a data-toggle="modal" id="1" href="#myModal"><script type="text/javascript">getRandomImage(random_images_array, 'images/portfolio/')</script></a>
<a data-toggle="modal" id="2" href="#myModal"><script type="text/javascript">getRandomImage(random_images_array, 'images/portfolio/')</script></a>
<a data-toggle="modal" id="3" href="#myModal"><script type="text/javascript">getRandomImage(random_images_array, 'images/portfolio/')</script></a>
<a data-toggle="modal" id="4" href="#myModal"><script type="text/javascript">getRandomImage(random_images_array, 'images/portfolio/')</script></a>
<a data-toggle="modal" id="5" href="#myModal"> <script type="text/javascript">getRandomImage(random_images_array, 'images/portfolio/')</script></a>
<a data-toggle="modal" id="6" href="#myModal"> <script type="text/javascript">getRandomImage(random_images_array, 'images/portfolio/')</script></a>
<a data-toggle="modal" id="7" href="#myModal"><script type="text/javascript">getRandomImage(random_images_array, 'images/portfolio/')</script></a>
</div>
</div>
I'm pretty new to javascript so sorry if this is a question thats been answered already or one that is a super easy fix我对 javascript 还很陌生,如果这是一个已经回答的问题或者一个超级简单的解决方法,我很抱歉
You could just splice the selected image out of your array, then it won't be available on the next iteration:您可以将所选图像从数组中拼接出来,然后在下一次迭代中将不可用:
function getRandomImage(imgAr, path) {
path = path || 'images/portfolio/'; // default path here
var num = Math.floor( Math.random() * imgAr.length );
var img = imgAr[ num ];
// remove the selected image
imgAr.splice(num, 1);
var imgStr = '<img src="' + path + img + '" alt = "">';
document.write(imgStr); document.close();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.