javascript - 不明白为什么我的 setInterval + jQuery 不起作用

标签 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 = 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/

关于javascript - 不明白为什么我的 setInterval + jQuery 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29519146/

相关文章:

javascript - 如何使用 JavaScript 检测 IFrame 更改 src

jquery - Fuelux 向导验证输入

javascript - SetInterval mySQL 每秒查询一次

javascript - 将html文本设置到textarea js中

javascript - 文件上传表单字段验证

javascript - 使用 jQuery 选中一个框

javascript - 在树莓派上使用 Webiopi 开发网页

javascript - 每次删除 DOM 元素(获取后)

JavaScript时钟: time interval conflicts

javascript - 从 ES 6 中的对象获取一些属性的单行代码