我有一个这样的脚本:

<span>Famous Quote:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script language="JavaScript">
var Quotation=new Array() // do not change this!
Quotation[0] = "Time is of the essence! Comb your hair.";
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.";
Quotation[10] = "Things are only impossible until they're not.";
var Q = Quotation.length;
var whichQuotation=Math.round(Math.random()*(Q-1));
function showQuotation(){document.write(Quotation[whichQuotation]);}
showQuotation();
</script>

如何将引号放在自己的文件而不是源代码中?这是一个示例:http://mydomain.go/quote.js

最佳答案

您可以使用模块加载器将代码拆分为不同的文件。
index.html内容:

<script data-main="scripts/main.js" src="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.15/require.js"></script>
scripts/main.js内容:
require(['quotations'], function (quotations) {
    var whichQuotation = Math.floor(Math.random() * quotations.length);
    function showQuotation(){
        document.write(quotations[whichQuotation]);
    }
    showQuotation();
});
scripts/quotations.js内容:
define(function () {
    return [
        "Time is of the essence! Comb your hair.",
        "Sanity is a golden apple with no shoelaces.",
        "Repent! The end is coming, $9.95 at Amazon.",
        "Honesty blurts where deception sneezes.",
        "Pastry satisfies where art is unavailable.",
        "Delete not, lest you, too, be deleted.",
        "O! Youth! What a pain in the backside.",
        "Wishes are like goldfish with propellors.",
        "Love the river's \"beauty\", but live on a hill.",
        "Invention is the mother of too many useless toys.",
        "Things are only impossible until they're not."
    ];
});

JavaScript没有import语句。很难在<script>标签之间拆分代码,因为像Quotation这样的变量将成为全局变量。因此,如果在您网站上工作的其他任何人都试图定义一个名为Quotation的变量,那么您俩都会被搞砸。使用模块加载器允许您共享报价单,而无需使用该变量。

我还修复了您的随机索引算法。

08-18 13:01