代码之家  ›  专栏  ›  技术社区  ›  Ry-

使用JQuery使用计时器遍历元素

  •  5
  • Ry-  · 技术社区  · 17 年前

    我试图使用JQuery来迭代许多<李>对象使用计时器,即-每5秒,我想访问下一个<李>我的目标<ul>。

    我知道您可以使用.each函数进行迭代,但我无法将计时器与之集成,以逐个迭代每个函数。

    我尝试了以下方法,但没有正常工作。它不断地给我最后的元素。我认为这是因为setTimeout不是连续的。

    $("#div_image_thumb ul li").each(function(){    
      var myLIobj = $(this);
      setTimeout(function(){doThis(myLIobj);}, 5000);
    });
    
    5 回复  |  直到 17 年前
        1
  •  15
  •   Fabian    17 年前

    约翰·菲舍尔的方法看起来不错。但是如果你想坚持jQuery的each,这是非常优雅的,试试这个(根据JasonWoof的提示将超时设置为5s、10s等):

    $("#div_image_thumb ul li").each(function (i) {
        var $li = $(this);
        setTimeout(function () { doThis($li); }, 5000 * (i + 1));
    });
    
        2
  •  7
  •   John Fisher    17 年前

    var elements = $("#div_image_thumb ul li");
    var index = 0;
    
    var doNext = null;
    doNext = function() {
      var element = elements.eq(index);
      // do work 
      if (index < elements.length) {
        index++;
        setTimeout(doNext, 5000);
      }
    }
    
        3
  •  3
  •   gnarf    17 年前

    根据您对已接受答案的评论,您希望继续在元素集合中循环,为此,您可以使用setInterval和一些帮助函数

    $(function() {
      var $lis = $("#div_image_thumb ul li");
      var index = 0;
    
      // setup a function to show the current one and increase the index
      var doNext = function() { 
        // assuming doThis is defined somewhere else.
        doThis($lis.eq(index));
        // increment the index - if it is beyond the number of li's - reset it to 0
        if (++index >= $lis.length) index = 0;
      };
    
      // call it once as we load
      doNext();
      // set it up to be called every 5000 ms
      setInterval(doNext, 5000);
    });
    
        4
  •  0
  •   JasonWoof    17 年前

    我认为您的代码存在的问题是,您将许多计时器设置为同时过期(从现在起5秒)

        5
  •  0
  •   BlueDreaming    10 年前

    我发现这是一个非常有用的项目。虽然我知道这是旧的,但我发现这个小技巧有助于构建一个可以用于不同项目集的函数。我在一个页面上有一些图库,我希望能够全面使用这些图库。我不确定这是否是多余的Gnarf的优秀答复旁边。也许我对Java脚本很差劲。我决定需要一个参数,并根据ECSMA2015之前的标准设置该参数的默认值,因此这应该适用于旧版本。

    它的实用性是,我可以在js初始化期间初始化它,并根据我可能在的页面向它提供任何信息,从而使我能够轻松地在不同的对象之间循环。

         function gallery($lis) {
      $lis = typeof a !== 'undefined' ? $lis : $("#div_image_thumb ul li");
      var index = 0;
    
      // setup a function to show the current one and increase the index
      var doNext = function() {
        // assuming doThis is defined somewhere else.
        doThis($lis.eq(index));
        // increment the index - if it is beyond the number of li's - reset it to 0
        if (++index >= $lis.length) index = 0;
      };
    
      // call it once as we load
      doNext();
      // set it up to be called every 5000 ms
      setInterval(doNext, 5000);
    };