javascript - 为什么这个 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>
如果它正在工作,则每次访问/刷新页面时,应随机显示其中一个引号。虽然他们根本不会出现。
解决方案
您的对象有错字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>
推荐阅读
- ruby-on-rails - Heroku 推送被拒绝,无法通过 Bundler #2 安装 gem
- python - Django 自定义字典响应
- resttemplate - 使用 Spring resttemplate 记录请求和响应
- python - 在 linux 的 80 端口上运行烧瓶
- javascript - 谁能帮我分离世博会应用程序
- sql - 如何从给定季度计算上一季度和下一季度?
- r - 从另一个数据帧中减去数据帧
- ios - Swift:AppDelegate func 应用程序调用但接下来会发生什么?
- codeigniter - 在 codeigniter 中使用 dropzone 上传没有表单操作的图像
- ruby-on-rails - webmock中post方法的动态参数