随机引用超链接脚本?

时间:2012-06-12 00:36:08

标签: javascript html string dom random

您好我一直在试图弄清楚如何使用随机引用脚本,其中每个引用都是在超链接上转到不同的页面。到目前为止,这是我用于引号的示例。有没有办法让每个引用都有自己的超链接?

<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>

1 个答案:

答案 0 :(得分:0)

此脚本将使用带有随机引用和相应href:

<a>标记替换自身
<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

如果您只想将脚本放在您想要链接的位置,并且您只想在页面上使用一次,这是最好的方法。如果你想在页面上多次使用它,你可以做一些不同的操作,这样你就不需要多个脚本副本。