2016-12-17 35 views
2

我正在尝试构建一个广告系统,其中每秒都会检查新的可用广告,并仅在前一个广告完成显示时才显示它们。 (每个广告都有一个名为'time'的属性,它指定了它应该显示的秒数)jQuery在间隔函数内更改DOM不会停留

我使用'setInterval()'实现了程序,并且每当有一个开放的插槽时,我都会为广告加载一个模板使用'.load()',使用'.html()'和'.attr(“src”,...)'将文本和图像更改为广告的文本和图像。

当运行文件时,广告(现在只有一个)会显示一秒(应该是四秒),然后将DOM恢复为来自'template.html'的原始文本和图像。此操作可以无限次执行,而每隔四秒钟,广告就会显示一次,以瞥见片刻,然后DOM恢复。

我在这里阅读了很多关于类似问题的帖子,但没有提供针对这个特定问题的解决方案。

这里就是广告对象存储在播放列表:

{name: "msg1", 
texts: {txt1: "First ad!", 
     txt2: "Come and buy our product!", 
     txt3: "It's top secret...", 
     txt4: "So it has to be good ;)"}, 
images: {img1: "./topSecret.png", 
      img2: "http://in5d.com/wp-content/uploads/2015/03/zdhstrrst.jpg"}} 

下面是使用jQuery的时间间隔内的DOM变化:

$(document).ready(function(){ 
    var iterator = 0; 
    var count = 1; 
    setInterval(function(){ 
     count--; 
     var infiniteLoopPreventor = playlist.length; 
     while(infiniteLoopPreventor >0 && count == 0){ //make sure no infinite loop and no previous msg is being displayed 
      var now = new Date(); 
      var currentMsg = playlist[iterator]; 
      for(var timeSet in currentMsg.timeSets){ 
       if(currentMsg.timeSets[timeSet].startDate.getTime()<=now.getTime() && 
        currentMsg.timeSets[timeSet].endDate.getTime()>=now.getTime() && 
       currentMsg.timeSets[timeSet].days[now.getDay()] == 1 && 
       currentMsg.timeSets[timeSet].startTime<=now.getHours() && 
       currentMsg.timeSets[timeSet].endTime>=now.getHours()){ 
        //display message 
       $("#result").load(currentMsg.template); 
       for(var txt in currentMsg.texts){ 
        $("div#"+txt).html(currentMsg.texts[txt]); 
       } 
       for(var img in currentMsg.images){ 
        $("img#"+img).attr("src", currentMsg.images[img]); 
       } 
       count = currentMsg.time; 
       break; //from the for loop which iterates over time sets. 
      } 
     } 
     iterator = (iterator + 1) % playlist.length; 
     infiniteLoopPreventor--; 
    } 
}, 1000); 
}); 

滚过帖子询问类似的问题,提出了一些建议,其中提出至于为什么会发生,但没有提供适当的解决方案。建议的原因是: - 更改不会因为html从另一个页面加载而粘住。 - 异步函数。 - 间隔问题,可以通过使用clearInterval()来解决,它不适合我的问题,因为我不希望在任何给定时间停止间隔。

我非常感谢您的见解。

回答

1

我终于找到了解决方案!

问题出于某种原因与.html()和.attr()。

我改变了代码,以便它们作为.load()回调函数的一部分执行,并且它可以工作。

我仍然会理解为什么旧版本无法正常工作的解释。与此同时,这里是新的代码:

$("#result").load(currentMsg.template, function(){ 
    for(var txt in currentMsg.texts){ 
     $("div#"+txt).html(currentMsg.texts[txt]); 
    } 
    for(var img in currentMsg.images){ 
     $("img#"+img).attr("src", currentMsg.images[img]); 
    } 
});