为什么不将Javascript函数打印到我的HTML文档中?

时间:2019-02-09 07:14:13

标签: javascript html

我正在尝试创建一个输出随机Mark Twain引号的HTML页面。我在单独的(链接的)Javascript文件中设置了函数和引号数组。无论出于何种原因,我都无法将输出显示在HTML文档中。

*编辑以添加:我很抱歉没有更好的研究,并发现在这种情况下区分大小写很重要。我是新手:)

这是我的Javascript代码。

// Quotes
var quotes = [
["The size of a misfortune is not determinable by an outsider's measurement of it but only by the measurements applied to it by the person specially affected by it. The king's lost crown is a vast matter to the king but of no consequence to the child. The lost toy is a great matter to the child but in the king's eyes it is not a thing to break the heart about."],
["Trivial Americans go to Paris when they die."],
["There isn't time -- so brief is life -- for bickerings, apologies, heartburnings, callings to account. There is only time for loving -- & but an instant, so to speak, for that."],
["Thunder is good, thunder is impressive; but it is lightning that does the work."],
["Everyone is a moon, and has a dark side which he never shows to anybody."]
];

// Generate a random number from the array
function random_item(quotes) {
  return quotes[math.floor(math.random()*quotes.length)];
}

这是我的HTML代码,其中的输出无效。我没有包含全部内容,因为这是唯一相关的部分。

<div id="quotes">
   <script>
   document.write(random_item(quotes));
   </script>
   </div>

如果该页面有效,则每次访问/刷新页面时,其中的引号之一应随机显示。他们根本不会出现。

1 个答案:

答案 0 :(得分:0)

您有一个Math对象的错字。

并考虑避免将脚本放入div

// Quotes
var quotes = [
["The size of a misfortune is not determinable by an outsider's measurement of it but only by the measurements applied to it by the person specially affected by it. The king's lost crown is a vast matter to the king but of no consequence to the child. The lost toy is a great matter to the child but in the king's eyes it is not a thing to break the heart about."],
["Trivial Americans go to Paris when they die."],
["There isn't time -- so brief is life -- for bickerings, apologies, heartburnings, callings to account. There is only time for loving -- & but an instant, so to speak, for that."],
["Thunder is good, thunder is impressive; but it is lightning that does the work."],
["Everyone is a moon, and has a dark side which he never shows to anybody."]
];

// Generate a random number from the array
function random_item(quotes) {
  return quotes[Math.floor(Math.random()*quotes.length)];
}

document.querySelector('#quotes').innerText = random_item(quotes);  // use instead of document.write
<div id="quotes">
   </div>