【问题标题】:Constant script -> change src iframe (1min, 5min) + jQuery常量脚本 -> 更改 src iframe (1min, 5min) + jQuery
【发布时间】:2014-11-26 22:03:11
【问题描述】:

我在用 jQuery 编写脚本时遇到问题。

我的页面中有一个iFrame 需要更改。
iframe 的来源必须是http://www.example1.com 一分钟,然后切换到http://www.example2.com 五分钟。这是一个恒定循环。但是我该怎么做呢?

我现在有:

jQuery(document).ready(function () {
    setTimeout(function() {
        if($('#iframe').attr('src') == "http://www.example1.com")
        {
            $('#iframe').attr('src',"http://www.example2.com");
        }
        else
        {
            $('#iframe').attr('src',"http://www.example1.com");
        }
    }, 10000);
});

但这并没有多大作用。而且它只运行一次..

【问题讨论】:

  • 将 iframe 元素替换为新元素比修改 src 属性更好。修改 src 属性将在浏览器历史记录中创建一个条目。

标签: javascript jquery loops iframe settimeout


【解决方案1】:

我相信这会奏效。每次调用其中一个函数时,它都会为另一个函数设置一个新的超时。您最初显示 1,然后设置 1 分钟超时。当该超时到期时,将显示 2,并将新的超时设置为 5 分钟,此时,将再次显示 1。

function show1() { 
    iframe.attr('src', 'http://www.example1.com');
    setTimeout(function() { show2(); }, 1000 * 60);
}
function show2() { 
    iframe.attr('src', 'http://www.example2.com');
    setTimeout(function() { show1(); }, 1000 * 60 * 5);
}

jQuery(document).ready(function() {
    show1();
});

【讨论】:

  • @nielsv 在全局函数中不需要,最好在闭包中使用函数。
  • @Cheery 好点——我仍然坚持使用命名函数,这样更容易看到你在做什么,但将它们保持在 jQuery 函数中将有助于保持全局命名空间的清洁。
【解决方案2】:

将 iframe 的初始 src 设置为 http://www.example1.com 和 ...

jQuery(document).ready(function () {
   var runme = function() {
      var iframe = $('#iframe');

      setTimeout(function() { // first callback
         iframe.attr('src', 'http://www.example2.com');
      }, 1000 * 60);          // change to example2 after 1 minute

      setTimeout(function() { // second callback
         iframe.attr('src', 'http://www.example1.com');
         runme();             // loop
      }, (1000 + 5000) * 60); // change to example1 after 6 minutes (1 + 5)
   };

   runme();
});

这段代码准备了两次超时,一个回调函数在 1 分钟后执行,第二个回调在 1 + 5 = 6 分钟后执行。第二个回调“重新武装”这两个超时等等..

如果你不想设置初始src,代码可以写成

jQuery(document).ready(function () {
   var runme = function() {
      var iframe = $('#iframe');

      iframe.attr('src', 'http://www.example1.com');  // set to example1

      setTimeout(function() {
         iframe.attr('src', 'http://www.example2.com');
         setTimeout(runme, 5000 * 60); // repeat after 5 minutes 
      }, 1000 * 60);          // change to example2 after 1 minute
   };

   runme();
});

【讨论】:

    【解决方案3】:
    (function () {
        var iframe = document.getElementById('iframe')
            , urlA = 'http://www.example1.com'
            , urlB = 'http://www.example2.com'
            , delayA = 60000
            , delayB = 300000
            , delay = iframe.getAttribute('src') === urlA ? delayA : delayB
            , timeoutCallback = function () {
                iframe.setAttribute('src', iframe.getAttribute('src') === urlA ? urlB : urlA);
                delay = delay === delayA ? delayB : delayA;
    
                // Set new timeout with updated delay
                setTimeout(timeoutCallback, delay)
            };
    
        // Start.
        setTimeout(timeoutCallback, delay);
    }());
    

    【讨论】:

      【解决方案4】:

      您还可以创建一个间隔回调,每 100 毫秒检查一次是否该显示下一个内容。也许它比其他方法要复杂一些。

      但是,如果您将其作为外部脚本包含在内,则只需 3 行代码即可加载您想要的内容。

      作为 iframe 的替代方案,您还可以将外部文件加载到对象标记中。我在下面的演示中使用了它。也可以找到和jsFiddle一样的代码here

      如果您更喜欢 iframe,我已在 loadData 函数中添加了代码作为注释。

      (我在演示中将每个内容的时间设置为 1 分钟,但可以随意更改。)

      var timedLoader = (function ($) {
          
          var tick = 100; // 100ms
          
          var that;
          function Scheduler() {
              this.schedule = [];
              this.lastTick = (new Date()).getTime();
              this.currentTask = 0;
              this.currentDuration = 0;
              this.elapsed = 0;
              
              that = this;
              this.startTaskRunner();
          }
          
          Scheduler.prototype.startTaskRunner = function() {
              setInterval(this.taskRunner, tick);
          };
          
          Scheduler.prototype.taskRunner = function() {
              // elapsed time
              var now = (new Date()).getTime();
              that.elapsed = now - that.lastTick;
              
              var sched = that.schedule; // reference to schedule to shorten the code
              
              if ( sched.length > 0 ) {
                  // at least one task available
                  if ( that.currentDuration == 0 ) {
                      that.currentDuration = sched[that.currentTask].displayTime * 60 * 1000; // scale to milli seconds
                      console.log('start duration = ' + that.currentDuration);
                      console.log('task = ' + that.currentTask);
                      
                      loadData(sched[that.currentTask].url);
                  }
                  else
                  {
                      that.currentDuration -= that.elapsed;
                      //console.log(that.currentDuration);   
                      if (that.currentDuration <= 0) {
                          // total time elapsed
                          that.currentDuration = 0;
                          that.currentTask++;
                          
                          // check if rollover required
                          if (that.currentTask > sched.length-1) that.currentTask = 0;
                      }
                  }
              }
              
              that.lastTick = now; // copy new to old
          };
          
          // time in minutes
          Scheduler.prototype.addTask = function(url, time) {
              this.schedule.push({'url': url, 'displayTime': time});
          };
          
          var loadData = function (src) {
              $('#container').html('<object type="text/html" data="'+ src +'"></object>');
              //$('#container').html('<iframe src="'+ src +'"></iframe>');
          };
          
          return {
              loadData: loadData,
              Scheduler: Scheduler
          };
      })(jQuery);
      
      $(function () {
          //timedLoader.loadData('http://www.example.com/');
          
          var loader = new timedLoader.Scheduler(); // start and init scheduler
          loader.addTask('http://www.example.com/', 1); // url to load, time in minutes
          loader.addTask('http://www.example1.com/', 1);
          //loader.addTask('http://www.wikipedia.org/', 1);
      });
      object, iframe {
          width: 100%;
          height: 200px;
      }
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <div id="container"></div>
      
      <!-- <object type="text/html" data="http://www.example.com/" ></object>-->

      【讨论】:

        猜你喜欢
        • 2023-01-01
        • 2014-06-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-29
        • 2012-09-10
        • 1970-01-01
        相关资源
        最近更新 更多