2012-04-09 141 views
0

我想加載頁面加載的隨機視頻。這是我認爲可能會發揮作用的一些JavaScript。我不熟悉JavaScript,所以可能有更簡單的方法來做到這一點...任何想法?如果您使用數組嘗試在頁面加載時顯示隨機視頻

function random_video { 

    var string1 = '<div class="span4"><h3 class="meet">Meet the Makers</h3><iframe width="100%" height="200" src="http://www.youtube.com/embed/Ig-DbfPoz3o" frameborder="0" allowfullscreen></iframe></div>'; 

    var string2 = '<div class="span4"><h3 class="meet">Meet the Makers</h3><iframe width="100%" height="200" src="http://www.youtube.com/embed/estPhyfBGho" frameborder="0" allowfullscreen=""></iframe></div>'; 

    var string3 = '<div class="span4"><h3 class="meet">Meet the Makers</h3><iframe width="100%" height="200" src="http://www.youtube.com/embed/6JL4hpnZklk" frameborder="0" allowfullscreen=""></iframe></div>'; 

    var number = Math.floor((Math.random()*3)+1); 

    if (number == 1) { 
     document.write(string1); 
    } else (number == 2) { 
     document.write(string2); 
    } else (number == 3) { 
     document.write(string3); 
    } 

}; 
+1

的if/else條件需要更多的IFS你的(如:'否則,如果(...')。 – j08691 2012-04-09 21:17:07

回答

4

會更普及,更容易增加更多視頻:

var videos = [ 
    'Ig-DbfPoz3o', 
    'estPhyfBGho', 
    '6JL4hpnZklk' 
]; 

var index=Math.floor(Math.random() * videos.length); 
var html='<div class="span4"><h3 class="meet">Meet the Makers</h3><iframe width="100%" height="200" src="http://www.youtube.com/embed/' + videos[index] + '" frameborder="0" allowfullscreen></iframe></div>'; 
document.write(html); 
+0

隨機化邏輯稍微偏離了一點,它應該是'Math.floor(Math.random()* videos.length)',這會給出1個小於數組長度的隨機數,這個數是完美的由於數組長度(在這個例子中)是3,但是第三項的索引是'2'。 – pseudosavant 2012-04-09 21:26:25

+0

yup,你擊敗了我,現在修好了。謝謝! – ampersand 2012-04-09 21:29:13

+0

你搖滾。完全工作。 – 2012-04-13 23:57:15

相關問題