2016-10-03 43 views
-1

好吧,所以我用JavaScript隨機顯示圖像在我的網格使用數組我有的問題是,因爲它抓住一個隨機圖像,有時它抓住了相同的圖像兩次。我會後我下面的代碼,但我只是在尋找一個解決方案,以便一旦它顯示的圖像也不會顯示圖像再次我已經做了一個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

保留已經顯示的索引數組。如果'random'函數返回已經存在於該數組中的東西,則獲取另一個隨機數,直到它不在數組中。 – dman2306

+0

生成一個非重複數字的隨機數組然後循環,看到這個http://stackoverflow.com/questions/18806210/generating-non-repeating-random-numbers-in-js – bryan60

+0

或者你可以初始[洗牌]( http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array)數組,然後只是通過它循環 – j08691

回答

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(); 
} 
+0

很高興幫助@AustinBeale :) –

相關問題