setTimeout不适用于jquery.each,这 [英] setTimeout not working with jquery.each, this

查看:87
本文介绍了setTimeout不适用于jquery.each,这的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在迭代表的单元格时在jquery .removeClass调用之间添加延迟.单元格可以正常显示,没有setTimeout,但是使用setTimeout可以中断代码.我在做什么错了?

I'm trying to add a delay between the jquery .removeClass calls while iterating through the cells of a table. The cells display properly with no setTimeout, but with setTimeout the code breaks. What am I doing wrong?

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

推荐答案

尝试一下:

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

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

It's generally a bad practice to pass a string to setTimeout() and also I don't think you can pass any variables when using it that way.

我也将其包装在一个闭合符中,以确保that始终适用于正确的元素并且不会被替换.

I have also wrapped it in a closure to ensure that that always applies to the right element and is not replaced.

尽管如此,就像NiftyDude所说的那样,您可能希望传递索引并使用该索引依次显示每个元素.

Although, like NiftyDude says you might want to pass in the index and use that to display each element in turn.

工作示例- 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不适用于jquery.each,这的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆