好吧所以我使用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();
}
这是我的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>
我对javascript很新,很抱歉,如果这个问题已经得到解答,或者是一个非常容易解决的问题
答案 0 :(得分:1)
您可以将所选图像拼接出阵列,然后在下一次迭代中无法使用:
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();
}