【发布时间】:2016-09-11 16:54:07
【问题描述】:
我的目标是有一个按钮,点击时会显示一个随机报价。我已经创建了一个 JSON 对象来存储我的报价,并编写了一个函数来随机选择和打印对象中的报价。
HTML sn-p - 按钮(Bootstrap 等)
<div class="row" id="quotebox">
<div class="text-center">
<button class="btn btn-default" onclick ="randomQuote()"type="submit">Hit Me Baby One More Time</button>
</div>
</div>
存储 5 个引号的 JSON 对象
var quotesList = [{
quote: "Planting popcorn does not produce more popcorn",
person: "Farmer Ted"
}, {
quote: "White whale, bad whale",
person: "Confucious (Moby Dick)"
}, {
quote: "Use the strobe function to disorientate your attacker",
person: "Flashlight"
}, {
quote: "Apply liberally to your erogenous zones",
person: "Spice Bomb"
}, {
quote: "Help me, I'm bleaching",
person: "The Great Barrier Reef"
}];
最后是打印随机引用的函数(由onClick触发)
function randomQuote() {
var listLength = Object.keys(quoteList).length;
var randVal = Math.floor(Math.random() * listLength);
document.write(quotesList[randVal]);
}
上面的两个 sn-ps 组成了我的整个 JavaScript 代码。
【问题讨论】:
-
有史以来最好的标题。没有认真避免噪音,在文本和标题中,对读者没有好处的东西,诅咒可能属于这一类。
-
var listLength = quoteList.length;是您所需要的长度。如果您希望能够多次点击,则不能使用document.write()。 -
@HopefullyHelpful 是的。加上标题可能是说
random quote generator,而不是random code generator。显示提问者的关注程度 - 难怪它在简单编码方面存在问题。
标签: javascript json random generator quote