<!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。但是,当我点击按钮时,文本不会显示。我的代码中有什么错误/缺失?
答案 0 :(得分:3)
您只需要确保在遇到脚本之前引用了JQuery库,然后在此行中移动单个括号:
var RandomNumber = Math.floor(Math.random())*Quotes.length;
所以它是:
var RandomNumber = Math.floor(Math.random()*Quotes.length);
通过移动右括号以使其在Quotes.length
之后出现,确保生成的随机数(从0到1)乘以向下舍入之前的数组长度。如果您不这样做,随机数将始终向下舍入为0.
<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;
答案 1 :(得分:1)
Math.floor(Math.random())总是返回0,所以你乘以它的任何东西都是0
答案 2 :(得分:1)
这是一些有一些修复的工作示例。
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)