【问题标题】:Issues with setTimeout() inside jQuery .eachjQuery .each 中的 setTimeout() 问题
【发布时间】:2012-02-06 12:27:35
【问题描述】:

以下代码将无法正常工作。我尝试了不同的变体并到处搜索,但没有运气。

i = 1;
var timer = new Array();
jQuery('a').each(function($) {
    i++;
    timer[i] = setTimeout(jQuery(this).remove(), i * 5000)
})

【问题讨论】:

  • 下面的代码不能正常工作。你想让它做什么?我假设您的问题是您立即致电jQuery(this).remove()
  • 还要注意,传递给each的第一个参数实际上是被选元素集合中DOM元素的索引。这意味着您不必维护单独的计数器。 More information in the documentation.

标签: jquery settimeout each


【解决方案1】:

setTimeout 接受 javascript 语句而不是 jQuery(this).remove() 的返回值:P 见this link

您可以只使用function(){stuff},但不确定是否会在您想要的时候处理jQuery(this)

【讨论】:

    【解决方案2】:

    Felix 已经在 cmets 中暗示过这个问题,但我会展开。

    timer[i] = setTimeout(jQuery(this).remove(), i * 5000)
    

    您的问题在于您正在调用jQuery(this).remove() 并将其返回值传递给您的setTimeout。假设您打算在超时到期时运行它。如果是这种情况,您需要将其包装在一个函数中,以便将该函数传递给setTimeout 并在计时器到期时执行。

    var $el = jQuery(this);
    
    timer[i] = setTimeout(function(){
        $el.remove()
    }, i * 5000)
    

    【讨论】:

      【解决方案3】:

      用函数包装删除元素

      i = 1;
      var timer = new Array();
      jQuery('a').each(function($) {
          i++;
          var thiz = jQuery(this);
          timer[i] = setTimeout(function() { thiz.remove(); }, i * 5000);
      })
      

      【讨论】:

        【解决方案4】:

        setTimeout(或setInterval)的第一个参数需要是对函数(或字符串,但您不想使用字符串语法)的引用。

        不是将函数作为参数传递,而是调用函数并传递其结果。如果删除括号,您将传递对函数的引用:

        timer[i] = setTimeout(jQuery(this).remove, i * 5000) 
        

        但是,当函数实际运行时,您将开始遇到this 是错误的问题。试试这样的:

        var i = 1,
            timer = [];
        jQuery('a').each(function($) {
            i++;
            var $this = jQuery(this);
            timer[i] = setTimeout(function() {$this.remove();}, i * 5000)
        })
        

        这利用了闭包的工作方式,即传递给setTimeout 的匿名函数在运行时将有权访问$this 变量,即使声明$this 的函数已经完成届时执行。

        请注意,使用[] 声明数组比使用new Array() 更好。

        还要注意,您将 i 初始化为 1,然后在使用它之前将其递增,这样您添加到数组中的第一个元素将是 timer[2]。您可能应该将其初始化为 0,然后在设置每个计时器后将其递增。

        【讨论】:

          【解决方案5】:

          尝试:

          <html>
          <body>
          <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
          <a href="#">a</a>
          <a href="#">a</a>
          <a href="#">a</a>
          <a href="#">a</a>
          <a href="#">a</a>
          <a href="#">a</a>
          <script>
          i = 1;
          var timer = new Array();
              jQuery('a').each(function($) {
              i++;
              timer[i] = setTimeout(jQuery.proxy(function(){jQuery(this).remove();},this), i * 500);
          })
          </script>
          </body>
          </html>
          

          【讨论】:

            猜你喜欢
            • 2011-05-22
            • 2011-11-26
            • 2011-01-07
            • 1970-01-01
            • 2010-11-19
            • 2021-06-08
            • 2013-09-28
            • 2013-09-27
            相关资源
            最近更新 更多