2012-06-12 101 views
0

嗨我一直在試圖弄清楚如何使用隨機報價腳本,其中每個報價是它的超鏈接去不同的頁面。到目前爲止,這是我用於引用的示例。有沒有辦法讓每個引用自己的超鏈接?隨機引用超鏈接腳本?

<script language="JavaScript"> 

var Quotation=new Array() // do not change this! 


Quotation[0] = "Test."; 
Quotation[1] = "Sanity is a golden apple with no shoelaces."; 
Quotation[2] = "Repent! The end is coming, $9.95 at Amazon."; 
Quotation[3] = "Honesty blurts where deception sneezes."; 
Quotation[4] = "Pastry satisfies where art is unavailable."; 
Quotation[5] = "Delete not, lest you, too, be deleted."; 
Quotation[6] = "O! Youth! What a pain in the backside."; 
Quotation[7] = "Wishes are like goldfish with propellors."; 
Quotation[8] = "Love the river's \"beauty\", but live on a hill."; 
Quotation[9] = "Invention is the mother of too many useless toys."; 


var Q = Quotation.length; 
var whichQuotation=Math.round(Math.random()*(Q-1)); 
function showQuotation(){document.write(Quotation[whichQuotation]);} 
showQuotation(); 
</script> 
+0

你如何確定要去哪個頁面? –

+1

是的。用JavaScript創建HTML或DOM元素。這是JS的典型用途之一,你應該能夠在網上找到大量的例子。例如:http://stackoverflow.com/questions/8005694/make-hyperlink-from-javascript –

+0

我不知道這個例子來自哪裏,但它是從同學那裏得到的,我在學校。 – user1450117

回答

0

該腳本將因<a>標籤與隨機報價和相應的href替換本身:

<script> 
(function(){ 

    var quotes = [ 
     {text: "Test.", href: "http://example.com"}, 
     {text: "Sanity is a golden apple with no shoelaces.", href: "http://example.com"}, 
     {text: "Repent! The end is coming, $9.95 at Amazon.", href: "http://example.com"}, 
     {text: "Honesty blurts where deception sneezes.", href: "http://example.com"}, 
     {text: "Pastry satisfies where art is unavailable.", href: "http://example.com"}, 
     {text: "Delete not, lest you, too, be deleted.", href: "http://example.com"}, 
     {text: "O! Youth! What a pain in the backside.", href: "http://example.com"}, 
     {text: "Wishes are like goldfish with propellors.", href: "http://example.com"}, 
     {text: "Love the river's \"beauty\", but live on a hill.", href: "http://example.com"}, 
     {text: "Invention is the mother of too many useless toys.", href: "http://example.com"} 
    ]; 

    var scripts = document.getElementsByTagName('script'); 
    var script = scripts[scripts.length - 1]; 
    var quote = quotes[Math.floor(Math.random()*quotes.length)]; 
    var a = document.createElement('a'); 
    a.href = quote.href; 
    a.appendChild(document.createTextNode(quote.text)); 
    script.parentNode.replaceChild(a, script); 

})(); 
</script> 

JSFiddle

這是爲了做到這一點,如果你只想把最好的辦法您想要鏈接的腳本,您只需要在頁面上顯示一次。如果您想在頁面上多次使用它,則可以稍微改變一點,以便不需要腳本的多個副本。

+0

好吧,使用我上面發佈的代碼,我會在哪裏使用上面的腳本實現這個? – user1450117

+0

@ user1450117你會在哪裏實施什麼?只需將此腳本複製並粘貼到您想要鏈接的位置,然後將所有「http://example.com」更改爲正確的URL。你也可以檢查JSFiddle。 – Paulpro

+0

我做了複製和粘貼,並改變了一切,但是當我去測試它時,它顯示爲空白頁面。 – user1450117