首页 > 解决方案 > 为什么这个 Javascript 函数没有打印到我的 HTML 文档中?

问题描述

我正在尝试创建一个输出随机马克吐温引号的 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>

如果它正在工作,则每次访问/刷新页面时,应随机显示其中一个引号。虽然他们根本不会出现。

标签: javascripthtml

解决方案


您的对象有错字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>


推荐阅读