我有一个按钮,显示数组中的引用和作者。每次单击按钮时,我都需要按钮显示新的引用/作者。连续两个引号/作者都没有!
window.onload = function()
{
//assign var to quoteText id contents
var quoteSpan = document.getElementById("quoteText");
//assign var to authorText id contents
var authorSpan = document.getElementById("authorText");
var oldQuoteIndex = -1;
var submitButton = document.getElementById('submit');
var quotes = [
{'text': 'I like milk!', 'author': '-Biff'},
{'text': 'Milk is nasty.', 'author': '-Jonn'},
{'text': 'What do you mean?', 'author': '-Jay'},
{'text': 'Milk. Mmm.', 'author': '-Don'},
{'text': 'Milk is bad.', 'author': '-Denny'}
];
//function determining random quote
function nextQuote() {
do
{
//picks random quote from quotes arraw
var newQuoteIndex = Math.floor(Math.random() * quotes.length);
} while (newQuoteIndex == oldQuoteIndex); //while index of newly chosen quote is the same as the index of old quote
quoteSpan.innerHTML = quotes[newQuoteIndex].text; //while HTML's quoteText has random quote
authorSpan.innerHTML = quotes[newQuoteIndex].author; //while HTML's authorText has random author
var oldQuoteIndex = newQuoteIndex; //while old index is same as new index
}
//when button is clicked, quotation function starts
submitButton.onclick = nextQuote;
}
答案 0 :(得分:0)
将随机索引行替换为以下内容,因为它没有完成任务。
var randomnumber = Math.floor(Math.random() * (quotes.length + 1));
这将返回[0 ... quotes.length]
之间的随机索引。
获取该索引处的对象后,将其删除以防止再次选择该对象。
答案 1 :(得分:0)
为什么要处理被选中的内容?
使用后立即将其删除。
基本示例:
var orgArr = [0,1,2,3,4,5];
var rand = orgArr.slice(0) //make a copy of the original
.sort(function (){ //sort array
return Math.random() > .5; // very basic shuffle function
});
while (rand.length) { //just looping to show the items being removed
var randomItem = rand.pop(); //get next random item and remove it
console.log(randomItem); //display it
}
如果发生点击,则执行弹出操作。