【问题标题】:Javascript function not displaying random messageJavascript函数不显示随机消息
【发布时间】:2017-10-25 13:18:58
【问题描述】:

对不起,我的格式很糟糕。我希望每次单击按钮时都会显示一个随机报价,而每次单击它时都会显示一个不同的报价。我是否需要在任何地方添加 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.floor(math.random()更改为Math.floor(Math.random()
  • 调试中的第 1 步 - 浏览器 developer 工具控制台 (F12) - 你的问题是 math !== Math

标签: javascript html css arrays function


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    在第 45 行,您输入了带有小写 M 的 Math。更改此行:

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

    到:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      • 1970-01-01
      • 2013-11-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多