-1

我是一个绝对的初学者,我正在尝试在任何浏览器(IE、FF、Chrome)中运行这段 JavaScript 代码。我正在使用 Firebug 作为调试器,但没有报告任何错误……感谢大家的宝贵时间。

function getQuote() {
    // Create the arrays
    quotes = new Arrays(4);
    sources = new Arrays(4);

    // Initialize the arrays with quotes
    quotes[0]  = "When I was a boy of 14, my father was so " + "ignorant...but when I got to be 21, I was astonished " + "at how much he had learned in 7 years.";
    sources[0] = "Mark Twain";
    quotes[1]  = "Everybody is ignorant. Only on different " + "subjects.";
    sources[1] = "Will Rogers";
    quotes[2]  = "They say such nice things about people at " + "their funerals that it makes me sad that I'm going to " + "miss mine by just a few days.";
    sources[2] = "Garrison Keilor";
    quotes[3]  = "What's another word for thesaurus?";
    sources[3] = "Steven Wright";

    // Get a random index into the arrays
    i = Math.floor(Math.random() * quotes.length);

    // Write out the quote as HTML
    document.write("<dl style='background-color: lightpink'>\n");
    document.write("<dt>" + "\"<em>" + quotes[i] + "</em>\"\n");
    document.write("<dd>" + "- " + sources[i] + "\n");
    document.write("<dl>\n");
}
4

2 回答 2

1

首先,你应该纠正这个:

// Create the arrays
quotes = new Arrays (4);
sources = new Arrays (4);

对此:

// Create the arrays
quotes = new Array (4);
sources = new Array (4);

此外,您需要在页面加载时调用此函数。将此行添加到脚本的末尾:

window.onload = getQuote;
于 2013-04-06T22:59:46.383 回答
0

我做了一些修改以获得更好的性能。您只需要调用该函数。

function getQuote() {
      // Create the arrays
      quotes = [
            {
                  quote: "When I was a boy of 14, my father was so ignorant...but when I got to be 21, I was astonished at how much he had learned in 7 years.",
                  source: "Mark Twain"
            },
            {
                  quote: "Everybody is ignorant. Only on different subjects.",
                  source: "Will Rogers"
            },
            {
                  quote: "They say such nice things about people at their funerals that it makes me sad that I'm going to miss mine by just a few days.",    
                  source: "Garrison Keilor"
            },
            {
                  quote: "What's another word for thesaurus?",
                  source: "Steven Wright"
            }
      ];

      // Get a random index into the arrays
      i = ~~(Math.random() * quotes.length);

      // Get body tag
      var body = document.getElementByTagName("body")[0],
            // Making a string to append to body
            htmlCode = "<dl style='background-color: lightpink'>\n" + 
                  "<dt>\"<em>" + quotes[i].quote + "</em>\"\n" +
                  "<dd>- " + quotes[i].source + "\n</dl>";

      // appending htmlCode to body
      body.innerHTML += htmlCode;

  }

我创建了一个对象数组以便更好地组织,因为报价和来源是相关数据。

我收集了一些关于javascript最佳实践的文章,看看:

希望能帮助到你...

于 2013-04-06T22:58:45.017 回答