【问题标题】:Bug when trying to pull a random quote from an array. [closed]尝试从数组中提取随机引用时出现错误。 [关闭]
【发布时间】:2015-11-10 04:36:24
【问题描述】:

我正在尝试使用随机数生成器从数组中显示一个随机引用,但我遇到了一个错误并且不确定原因。这就是我所拥有的。我知道这可能是重复的,但我觉得它应该打印,但不是。谢谢你的帮助。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Assignment 9</title> 
    <link href="images/avatar.png" rel="shortcut icon" type="image/png">
    <link href="css/stylesheet.css" rel="stylesheet" type="text/css">
    <script src="js/javascript.js" type="text/javascript"></script>
    <style type="text/css">
    </style>
    <script type="text/javascript">
    </script>
</head>
<body>
<header>
</header>
<aside>
</aside>
<div id="main">
<h1> Arrays and Coditional Statements</h1>

<h2> Quote of the Day</h2>
<p id="demo"></p>
<script>
function myFunction(){
var quote= ["It's not the size of the dog in the fight, It's the size of the fight in the dog",
"Love is the one thing that transcends time and space", "When it rains it pours", "Wake up slow", 
" Do not go gentle into that good night; Old age should burn and rave at close of day. Rage, rage against the dying of the light."
];


var randquote= quote[Math.floor(Math.random() * quote.length)];

document.getElementById("demo").innerHTML=randquote;
}
</script>




</div>
<footer>
</footer>
</body>
</html>

【问题讨论】:

  • 你永远不会打电话给myFunction()
  • 是的 - works 如果你真的调用了这个函数。

标签: javascript html arrays


【解决方案1】:

调用myFunction() 后,您的代码运行良好:

function myFunction(){
var quote= ["It's not the size of the dog in the fight, It's the size of the fight in the dog",
"Love is the one thing that transcends time and space", "When it rains it pours", "Wake up slow", 
" Do not go gentle into that good night; Old age should burn and rave at close of day. Rage, rage against the dying of the light."
];


var randquote= quote[Math.floor(Math.random() * quote.length)];

document.getElementById("demo").innerHTML=randquote;
}

myFunction();
&lt;p id="demo"&gt;&lt;/p&gt;

另一种方法(更简洁):

(function (){
    var quote= [
        "It's not the size of the dog in the fight, It's the size of the fight in the dog",
        "Love is the one thing that transcends time and space",
        "When it rains it pours",
        "Wake up slow", 
        "Do not go gentle into that good night; Old age should burn and rave at close of day. Rage, rage against the dying of the light."
    ];


    var randquote= quote[Math.floor(Math.random() * quote.length)];

    document.getElementById("demo").innerHTML=randquote;
})();
&lt;p id="demo"&gt;&lt;/p&gt;

【讨论】:

    猜你喜欢
    • 2021-09-18
    • 2017-05-15
    • 2021-03-15
    • 1970-01-01
    • 2014-03-06
    • 2023-02-09
    • 1970-01-01
    • 2022-01-23
    • 2010-09-24
    相关资源
    最近更新 更多