Javascript 函数不显示随机消息

标签 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>

最佳答案

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

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

关于Javascript 函数不显示随机消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44171202/

相关文章:

javascript - js函数不返回onclick

javascript - 需要帮助按钮从下拉列表中获取输入以进行重定向

javascript - 抖动子元素的尺寸以填充父元素

html - 带复选标记的无序列表 list-style-positions-outside 文本在左侧垂直对齐

javascript - 如何在 Holder.js 图像中使用 Bootstrap Glyphicons

html - 在 Bootstrap 中将图像定位在 div 标签上

javascript - 验证用户名和密码失败 - 客户端 session

javascript - 如何创建 Ember.MutableArray 的实例?

Javascript 脚本第一次不起作用,但之后就可以了

html - 下拉菜单手机打不开