【问题标题】:setTimeout not working with jquery.each, thissetTimeout 不适用于 jquery.each,这
【发布时间】:2012-05-23 18:41:05
【问题描述】:

我试图在遍历表的单元格时在 jquery .removeClass 调用之间添加延迟。单元格在没有 setTimeout 的情况下正确显示,但使用 setTimeout 时代码会中断。我做错了什么?

function reveal_board() {
$("td").each(function() {
    var t=setTimeout('$(this).removeClass("invisible")', 500);
});
}

【问题讨论】:

    标签: jquery settimeout each


    【解决方案1】:

    试试这个:

    function reveal_board() {
        $("div").each(function(index) {        
            (function(that, i) { 
                var t = setTimeout(function() { 
                    $(that).removeClass("invisible"); 
                }, 500 * i);
            })(this, index);
        });
    }
    

    将字符串传递给setTimeout() 通常是一种不好的做法,而且我认为这样使用时不能传递任何变量。

    我还将它包装在一个闭包中,以确保that 始终适用于正确的元素并且不会被替换。

    不过,就像 NiftyDude 所说,您可能希望传入索引并使用它来依次显示每个元素。

    工作示例 - http://jsfiddle.net/Cc5sG/

    编辑

    看起来你不需要关闭:

    function reveal_board() {
        $("div").each(function(index) {        
            var that = this;
            var t = setTimeout(function() { 
                $(that).removeClass("invisible"); 
            }, 500 * index);        
        });
    }
    

    http://jsfiddle.net/Cc5sG/1/

    【讨论】:

    • 抱歉编辑,我不小心投了反对票,不得不编辑,所以我可以再次投赞成票。
    • 究竟如何才能编写出如此优雅的 setTimeout 迭代方式。不幸的是,我只能投 1 票
    【解决方案2】:

    好吧,我遇到了同样的问题,我用这种方法解决了……但我不知道性能或其他什么,我在一个非常短的循环(最多 10 个元素)中使用它,它运行良好。 ..顺便说一句,我用它来添加一个类,所以我会让你弄清楚它给删除一个类提供了什么;)。

    var elements = $(".elements");
    var timeout;
    
    elements.each(function(e){
        timeout = setTimeout(function(index) {
           elements[elements.length-e-1].setAttribute('class', elements[elements.length-e-1].getAttribute('class')+' MY-NEW-CLASS');
        }, 500 * e);
    });
    

    【讨论】:

      【解决方案3】:

      首先,setTimeout 的第一个参数避免使用字符串,而是使用 anon 函数,因为它更易于调试和维护:

      $("td").each(function() {
          var $this = $(this);
          var t=setTimeout(function() {
             $this.removeClass("invisible")
          }, 500);
      });
      

      另外,我不太确定你想在这里实现什么(稍后更新你的问题,我会调整我的答案),但是如果你想在 500 毫秒后从每个 td 中删除 invisible 类可以互相使用index:

      $("td").each(function() {
          var $this = $(this);
          var t=setTimeout(function(index) {
             $this.removeClass("invisible")
          }, 500 * (index+1));
      });
      

      【讨论】:

        【解决方案4】:

        您的this 指向全局window

        function reveal_board() {
          $("td").each(function() {
            $this = $(this);
            var t=setTimeout(function(){$this.removeClass("invisible");}, 500);
          });
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-07-02
          • 1970-01-01
          • 1970-01-01
          • 2021-12-16
          • 2019-03-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多