我应该在Javascript / HTML中调整什么来使这个随机引用生成器工作?

时间:2017-01-08 20:04:01

标签: javascript jquery html html5

<!DOCTYPE html>
<html>
<head>
<title>Quote Gen</title>

<script src="jquery-3.1.1.min.js"></script>
<script>

var Quotes = ['Thousands of candles can be lighted from a single candle, and the life of the candle will not be shortened. Happiness never decreases by being shared.','Happiness is the art of never holding in your mind the memory of any unpleasant thing that has passed.','To be happy, we must not be too concerned with others.','Change your thoughts and you change your world.','hello'];
  function newQuote(){
  var RandomNumber = Math.floor(Math.random())*Quotes.length;
  $("#QuoteDisplay").text(Quotes[RandomNumber]);
  }
  </script>
  </head>
  <h5>
  Simple Quote Generator
  </h5>
  <body>
<p id = "QuoteDisplay">

</p>
  <button onclick="newQuote()">New Quote!</button>

</body>  
</html>

这是一个简单的报价生成器,我将其作为FreeCodeCamp的一部分构建。目的是基本上在用户点击Buttton时生成一个新的Quote。但是,当我点击按钮时,文本不会显示。我的代码中有什么错误/缺失?

3 个答案:

答案 0 :(得分:3)

您只需要确保在遇到脚本之前引用了JQuery库,然后在此行中移动单个括号:

var RandomNumber = Math.floor(Math.random())*Quotes.length;

所以它是:

var RandomNumber = Math.floor(Math.random()*Quotes.length);

通过移动右括号以使其在Quotes.length之后出现,确保生成的随机数(从0到1)乘以向下舍入之前的数组长度。如果您不这样做,随机数将始终向下舍入为0.

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Quote Gen</title>

<script src="jquery-3.1.1.min.js"></script>
<script>

var Quotes = ['Thousands of candles can be lighted from a single candle, and the life of the candle will not be shortened. Happiness never decreases by being shared.','Happiness is the art of never holding in your mind the memory of any unpleasant thing that has passed.','To be happy, we must not be too concerned with others.','Change your thoughts and you change your world.','hello'];
  
  function newQuote(){
    var RandomNumber = Math.floor(Math.random()*Quotes.length);
    $("#QuoteDisplay").text(Quotes[RandomNumber]);
  }
  
  </script>
  </head>
  <h5>
  Simple Quote Generator
  </h5>
  <body>
  <p id = "QuoteDisplay"></p>
  <button onclick="newQuote()">New Quote!</button>

</body>  
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

Math.floor(Math.random())总是返回0,所以你乘以它的任何东西都是0

答案 2 :(得分:1)

  • RandomNumber始终为0
  • 此外,使用小写的第一个字母声明Javascript变量是一个好习惯。
  • 如果您正在使用它,请坚持使用jQuery,如果您可以使用jQuery click事件,请避免在DOM上单击。

这是一些有一些修复的工作示例。

https://jsbin.com/meqetumini/edit?html,js,output

function newQuote(){
    var RandomNumber = Math.floor(Math.random()*Quotes.length);
    $("#QuoteDisplay").text(Quotes[RandomNumber]);
}

$('#new-quote-btn').click(newQuote)