我的问题是关于我正在研究的报价生成器。它也工作onload :),但我想省略下一个onclick随机选择的报价与最后显示的报价相同的情况。我希望它与众不同。谢谢你的提示。
这是我的js代码:
var quotes = [
{ text: "Memento mori",
autor: "Bractwo Męki Pańskiej" },
{
text: "Jeśli możesz sobie coś wymarzyć, możesz też to zrobić.",
autor: "Walt Disney"
},
{
text: "Wszystko jest możliwe. Niemożliwe wymaga po prostu więcej czasu.",
autor: "Dan Brown"
},
{
text: "Czerp z innych, ale nie kopiuj ich. Bądź SOBĄ",
autor: "Michel Quois"
},
{
text: "Kiedy łamiesz zasady, łam je mocno i na dobre.",
autor: "Terry Pratchett"
}
];
window.onload = function() {
quoteMachine.initialQuote()
};
var quoteMachine = {
initialQuote: function() {
var newInitialQuote = quotes[Math.floor(Math.random() * quotes.length)];
var newInitialQuoteText = newInitialQuote.text;
var newInitialQuoteAutor = newInitialQuote.autor;
document.getElementById("new-quote").innerHTML = newInitialQuoteText;
document.getElementById("autor").innerHTML = newInitialQuoteAutor;
}
};
这是工作示例:https://randome-quote-machine.glitch.me
正如我写的那样,我做错了,或者这些答案都没有奏效。这是codepen.io的链接,也许有人可以看看并帮助我:https://codepen.io/hubkubas/pen/oPoJba?editors=1010
您可以在变量中保留最后一个随机索引,然后在第二次单击随机化之后直到新随机变量与前一个随机变量不同。
设置一个全局变量,例如let previous = -1
然后:
let random = Math.floor(Math.random() * quotes.length);
while(previous == random)
{
random = Math.floor(Math.random() * quotes.length)
}
previous = random
var newInitialQuote = quotes[random];
也许你可以在数据中添加一个标志is_showed:
var quotes = [
{
showed: false,
text: "Memento mori",
autor: "Bractwo Męki Pańskiej"
},
{
showed: false,
text: "Jeśli możesz sobie coś wymarzyć, możesz też to zrobić.",
autor: "Walt Disney"
},
{
showed: false,
text: "Wszystko jest możliwe. Niemożliwe wymaga po prostu więcej czasu.",
autor: "Dan Brown"
},
{
showed: false,
text: "Czerp z innych, ale nie kopiuj ich. Bądź SOBĄ",
autor: "Michel Quois"
},
{
showed: false,
text: "Kiedy łamiesz zasady, łam je mocno i na dobre.",
autor: "Terry Pratchett"
}
];
window.onload = function() {
quoteMachine.initialQuote()
};
var quoteMachine = {
initialQuote: function(next) {
var rand_number = Math.floor(Math.random() * quotes.length);
var newInitialQuote = quotes[rand_number];
if (newInitialQuote.showed) {
var next = -1;
for (var i = 0; i < quotes.length; i++) {
if (quotes[next].showed == false) {
break;
}
}
if (next == -1) {
document.getElementById("new-quote").innerHTML = "Sorry I have not new quotes";
document.getElementById("autor").innerHTML = "John Doe";
return;
}
rand_number = next;
newInitialQuote = quotes[rand_number];
}
quotes[rand_number].showed = true;
var newInitialQuoteText = newInitialQuote.text;
var newInitialQuoteAutor = newInitialQuote.autor;
document.getElementById("new-quote").innerHTML = newInitialQuoteText;
document.getElementById("autor").innerHTML = newInitialQuoteAutor;
}
};