JavaScript不会在任何浏览器中显示

时间:2013-04-06 22:44:53

标签: javascript

我是一个绝对的初学者,我试图在任何浏览器(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");
}

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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中收集了一些关于最佳实践的文章,看看:

希望它有所帮助...