尝试从数组中提取随机引用时出错。

时间:2015-11-09 20:32:54

标签: javascript html arrays

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

<!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>

1 个答案:

答案 0 :(得分:0)

致电myFunction()后,您的代码完美运行:

&#13;
&#13;
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();
&#13;
<p id="demo"></p>
&#13;
&#13;
&#13;

另一种方法(更清洁一点):

&#13;
&#13;
(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;
})();
&#13;
<p id="demo"></p>
&#13;
&#13;
&#13;