Javascript函数不显示随机消息

时间:2017-05-25 02:12:44

标签: javascript html css arrays function

抱歉,我的格式很糟糕。我希望每次单击按钮时显示随机引用,每次单击时都会显示不同的引号。我是否需要在任何地方添加document.write或其他类似的东西?我确定这里和那里有一堆错误,但我只是想从函数中返回一个随机引用。

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Random quote</title>

    <style>

body {
    background-color: #fff;
    font-family: sans-serif;
    color: #28315C;
}

h1 {
    text-align: center;
}

button {
    border-color: #000;
    background-color: #88D0FE;
    color: #000;
    font-size: 20px;



}
</style>
</head>
<body>
    <script>

    var quotes = ['this is fortune 1',
                   'this is fortune 2',
                   'this is fortune 3',
                   'this is fortune 4',
                   'this is fortune 5',
                   'this is fortune 6',
                   'this is fortune 7', 
                  ];


        function newQuote(){

        var randomNumber = Math.floor(math.random() * (quotes.length));

        document.getElementById('quoteDisplay').innerHTML = quotes[randomNumber];


}

    </script>


</body>

    <div id="quoteDisplay"> 
    </div>
    <button onclick="newQuote()">New Quote</button>


</html>

2 个答案:

答案 0 :(得分:0)

首先,将math更改为Math。此外,如果您只想设置文字内容,则可以使用innerText属性而不是innerHTML。运行下面的代码段。

&#13;
&#13;
<script>
  var quotes = ['this is fortune 1',
    'this is fortune 2',
    'this is fortune 3',
    'this is fortune 4',
    'this is fortune 5',
    'this is fortune 6',
    'this is fortune 7',
  ];

  function newQuote() {
    var randomNumber = Math.floor(Math.random() * (quotes.length));
    document.getElementById('quoteDisplay').innerText = quotes[randomNumber];
  }
</script>

<div id="quoteDisplay">
</div>
<button onclick="newQuote()">New Quote</button>
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

在第45行,您使用小写字母M键入Math。更改此行:

var randomNumber = Math.floor(math.random() * (quotes.length));

为:

var randomNumber = Math.floor(Math.random() * (quotes.length));