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

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/

09-17 16:53