开发者

Pass array elements to settimeout function

I don't understand why the fadeOut works but the remove doesn't. I found out it's a problem with the array. I tried some combinations, but I can't make it work.

for (var i=0;i<fieldsblock.length;i++){
     $("#"+fieldsblock[i]+"_tr"+nid).fadeOut();
     t=setTimeout(function(){$("#"+fields开发者_JAVA技巧block[i]+"_tr"+nid).remove();},400); 
    }

Thanks.


It looks like you just need the remove to run once the fadeOut has completed. If that's the case, you don't need to use setTimeout. You can use a callback instead:

for (var i=0;i<fieldsblock.length;i++){
    $("#"+fieldsblock[i]+"_tr"+nid).fadeOut(function() {
        $(this).remove();
    });
}

The callback is executed whenever the animation is complete, so doing it this way means you won't have to change the setTimeout duration if you wanted to change the duration of the fade as well.


While I believe using the callback for jquery's fadeOut() method is correct in this case, you could still remove the element without it.

var block;

for (var i = 0; i < fieldsblock.length; i++) {
    // Get the element
    block = $("#" + fieldsblock[i] + "_tr" + nid);

    // Fade it out without using the callback for whatever reason
    block.fadeOut();

    // Wait 400ms to remove it
    setTimeout((function (blockToRemove) {
        return function () { blockToRemove.remove(); };
    })(block), 400);
}

Basically, (function (args...) { ... })(args...) lets you pass arguments to a function's local scope, which will "save the state" of the arguments you're working with. In the example above, we're passing block to the function's blockToRemove parameter, which then returns's another function that actually removes the element.

In this case it's definitely better to use the callback, but there are other times when someone could be looping through something where this would be very useful.


You've created a closure around the i variable. Closures capture the variable itself, not the value of the variable. So once these timeouts trigger, i will be equal to fieldsblock.length for all of them, which is not quite what you want.

In this particular case, James Allardice's answer is a good one, you might also need to add a delay() call if you want the remove to not happen right after fade out.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜