我无法弄清楚 $("identifier").remove
如何与 setTimeout()
配合使用。下面的代码尝试制作雪花飘落的动画
//construct a html string
var html_str = "<img class='snowflakes' src = 'snowflake1.png' style='position: absolute; left: " + String(pos_x) + "px'> "
//Append the element to field
var flake = $(html_str).appendTo('#field');
flake.animate({top: String(FIELD_SIZE-FLAKE_SIZE)+'px'},
drop_speed,
//callback function when finished animating
function(){
setTimeout(function(){flake.remove();},1000);
}
);
不明白怎么办
setTimeout(function(){flake.remove();},1000); //this works
setTimeout(flake.remove,1000); //but this doesn't remove the element
在我看来,两者应该执行相同的功能。这是怎么回事?
最佳答案
第二个不起作用,因为它是在全局上下文中执行的。这是一篇关于传递给 setTimeout 的函数中的 this
上下文的文章,按照 MDN (Check 'The "this" problem)'
如果这样编写,您的代码将会工作:
setTimeout(flake.remove.bind(flake),1000);
关于javascript - jQuery setTimeout() 回调不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42883797/