2012-06-12 58 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