Javascript Don';我不明白为什么我的setInterval+;jQuery没有';行不通

Javascript Don';我不明白为什么我的setInterval+;jQuery没有';行不通,javascript,jquery,setinterval,Javascript,Jquery,Setinterval,总而言之,我尝试创建一个随机引用生成器。我的代码很简单 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

总而言之,我尝试创建一个随机引用生成器。我的代码很简单

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

您必须将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);

您永远不会更改
randomQuote
的值。它在页面加载时只分配一次谢谢,我甚至没有注意到。您从未更改
randomQuote
的值。它在页面上只被分配了一次谢谢,我甚至没有注意到。这是一个JS提琴,我再次更新了代码,效果很好。谢谢你,这很好用…该死的,我仔细考虑了这个问题。这是一个JS提琴,我再次更新了代码,它很好用。谢谢你,这很好用…该死的,我想得太多了。