将数组元素传递给 settimeout 函数
我不明白为什么淡出有效但删除无效。我发现是数组的问题。我尝试了一些组合,但无法使其发挥作用。
for (var i=0;i<fieldsblock.length;i++){
$("#"+fieldsblock[i]+"_tr"+nid).fadeOut();
t=setTimeout(function(){$("#"+fieldsblock[i]+"_tr"+nid).remove();},400);
}
谢谢。
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(){$("#"+fieldsblock[i]+"_tr"+nid).remove();},400);
}
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看起来您只需要在
fadeOut
remove 即可> 已完成。如果是这种情况,则不需要使用setTimeout
。您可以改用回调:每当动画完成时就会执行回调,因此这样做意味着如果您想更改淡入淡出的持续时间,则不必更改
setTimeout
持续时间以及。It looks like you just need the
remove
to run once thefadeOut
has completed. If that's the case, you don't need to usesetTimeout
. You can use a callback instead: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.虽然我相信在这种情况下使用 jquery 的
fadeOut()
方法的回调是正确的,但您仍然可以删除没有它的元素。基本上,
(function (args...) { ... })(args...)
允许您将参数传递到函数的本地作用域,这将“保存您的参数的状态”正在与.在上面的示例中,我们将block
传递给函数的blockToRemove
参数,然后该参数返回实际删除元素的另一个函数。在这种情况下,使用回调肯定更好,但也有其他时候,有人可能会循环遍历某些内容,这会非常有用。
While I believe using the callback for jquery's
fadeOut()
method is correct in this case, you could still remove the element without it.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 passingblock
to the function'sblockToRemove
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.
您已经围绕 i 变量创建了一个闭包。闭包捕获变量本身,而不是变量的值。因此,一旦这些超时触发, i 将等于所有超时的
fieldsblock.length
,这并不完全是您想要的。在这种特殊情况下,James Allardice 的答案是一个很好的答案,如果您希望淡出后不立即发生删除,您可能还需要添加一个
delay()
调用。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.