2011-11-01 15 views
1

設置:jQuery的週期插件 - 顯示來自同一組的多個圖像瓦特/沒有重複

我有一組〜20個的圖像。我想一次顯示其中的6個,並使用jQuery Cycle插件隨機旋轉該組中的不同圖像。我已經拼湊出了一個解決方案,我將Cycle插件稱爲6次不同的時間,並將每個圖像列在6個div的每一箇中。目前的解決方案大致基於this question/answer

問題:

我不想重複的圖像顯示。現在,經常會有2個甚至3個重複同時顯示。這看起來很愚蠢!我假設這將涉及基於圖像顯示的某種重寫陣列(有沒有辦法分辨?),但我真的被困在如何去做。

任何幫助,將不勝感激!謝謝!

目前代碼:

$(document).ready(function(){ 
    var NumImages = 20, // Number of logos to show 
     FirstPart = '<img src="/DEV/demo/images/', 
     LastPart = '.jpg" height="50" width="100" />', 
     array = ['bali.sm',   'disney.sm', 'fisherprice.sm', 
       'fruit.of.loom.sm', 'gerber.sm', 'hamilton.beach.sm', 
       'hotwheels.sm',  'igloo.sm', 'magnavox.sm', 
       'matchbox.sm',  'mohawk.sm', 'playtex.sm', 
       'purina.sm',  'rca.sm', 'remington.sm', 
       'rubbermaid.sm', 'shark.sm', 'sony.sm', 
       'sunbeam.sm',  'tonka.sm'], // array with all image names 
     rnd, value, i; 

    for (i = 0; i < NumImages; i++) { // pick numbers 
     rnd = Math.floor(Math.random() * array.length); 
     value = array.splice(rnd,1)[0]; // remove the selected number from the array and get it in another variable 

     document.getElementById('pic1').innerHTML += (FirstPart + value + LastPart); 
     document.getElementById('pic2').innerHTML += (FirstPart + value + LastPart); 
     document.getElementById('pic3').innerHTML += (FirstPart + value + LastPart); 
     document.getElementById('pic4').innerHTML += (FirstPart + value + LastPart); 
     document.getElementById('pic5').innerHTML += (FirstPart + value + LastPart); 
     document.getElementById('pic6').innerHTML += (FirstPart + value + LastPart); 
    } 
    $("#pic1").cycle({ fx: 'fade', speed: 2000, timeout: 28000, random: 1, delay: -15000 }); 
    $("#pic2").cycle({ fx: 'fade', speed: 2000, timeout: 28000, random: 1, delay: -10000 }); 
    $("#pic3").cycle({ fx: 'fade', speed: 2000, timeout: 28000, random: 1, delay: -5000 }); 
    $("#pic4").cycle({ fx: 'fade', speed: 2000, timeout: 28000, random: 1, delay: 0 }); 
    $("#pic5").cycle({ fx: 'fade', speed: 2000, timeout: 28000, random: 1, delay: 5000 }); 
    $("#pic6").cycle({ fx: 'fade', speed: 2000, timeout: 28000, random: 1, delay: 10000 }); 
}); 
+0

也許[這個答案] (http://stackoverflow.com/questions/2380019/generate-8-unique-random-numbers-between-1-and-100)可能有幫助嗎? – Mottie

回答

0

我可能會建立一個臨時的數組來存儲我隨機生成的數字,然後每次檢查:

var tmparray = []; 
for (var i=0; i<NumImages; i++) { // pick numbers 
    rnd = -1; 
    while (tmparray.indexOf(rnd) == -1) { 
     rnd = Math.floor(Math.random() * array.length); 
    } 
    tmparray.push(rnd); 
    value = array.splice(rnd,1)[0]; 

    ... 

} // end for 
+0

...但請參閱http://stackoverflow.com/q/143847/901048關於使用'array.indexOf()' – Blazemonger

相關問題