Don'我不明白为什么我的setInterval+jQuery;不起作用

Don't understand why my setInterval + jQuery doesn't work

本文关键字:我的 为什么 setInterval+jQuery 不起作用 明白 Don      更新时间:2023-09-26

总之,我正在尝试使用一个随机报价生成器。我的代码很简单。。。

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);

http://jsfiddle.net/av1xg897/1/