总而言之,我正在尝试拥有一个随机报价生成器。我的代码非常简单...
var myQuotes = [
{
quote: "To err is human; to forgive, divine.",
cite: "Alexander Pope"},
{
quote: "Reports of my death have been greatly exaggerated.",
cite: "Mark Twain"}
];
var randomQuote = Math.floor(Math.random() * myQuotes.length);
$('.quote').html(myQuotes[randomQuote].quote); // #1
$('.cite').html(myQuotes[randomQuote].cite);
setInterval(function() {
$('.quote').fadeOut();
$('.quote').fadeIn().html(myQuotes[randomQuote].quote); // #2
}, 3000);
加载时,它显示#1 很好,但#2 似乎不起作用...它只是不断闪烁之前的相同内容,即#1 中的内容。我对此有什么不明白的地方?
最佳答案
您必须将 randomQuote 变量放入 setInterval 中,以便它更新:
setInterval(function() {
randomQuote = Math.floor(Math.random() * myQuotes.length);
$('.quote, .cite').fadeOut("slow", function() {
$('.quote').fadeIn("slow").html(myQuotes[randomQuote].quote);
$('.cite').fadeIn("slow").html(myQuotes[randomQuote].cite);
});
}, 3000);
关于javascript - 不明白为什么我的 setInterval + jQuery 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29519146/