我的目标是让按钮在点击时显示随机引用。我已经创建了一个JSON对象来存储我的引号并编写了一个函数来随机选择并打印来自对象的引用。
HTML片段 - 按钮(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]);
}
上面的两个片段构成了我的整个JavaScript代码。
答案 0 :(得分:0)
这是固定的JS。主要问题是您使用Object.keys(quoteList).length
来获取quoteList
的长度,即使它只是一个简单的数组。此外,您使用的是document.write
,这通常被视为不良做法。我通过将document.getElementById('quotebox').innerHTML
设置为带引号和作者的字符串来替换它。最后,您将整个引用对象写入屏幕,而不是访问引用对象的各个属性并从中构造字符串。
var $quoteBox = document.getElementById('quotebox');
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"
}
];
function randomQuote() {
var randIdx = Math.floor(Math.random() * quotesList.length);
var randQuote = quotesList[randIdx];
$quoteBox.innerHTML = "\"" + randQuote.quote + "\" - " + randQuote.person;
}