我正在尝试将以下JS代码段转换为CoffeeScript:
$(document).ready(function(){
window.setTimeout(function(){
$('#flash').slideUp('slow', function(){
$(this).remove();
})
}, 1000)
})
我试过了:
$(document).ready ->
window.setTimeout ->
$('#flash').slideUp 'slow', (-> $(this).remove()), 1000
导致以下JS代码:
(function() {
$(document).ready(function() {
return window.setTimeout(function() {
return $('#flash').slideUp('slow', (function() {
return $(this).remove();
}), 1000);
});
});
}).call(this);
看起来和我很相似,但它根本不起作用。片段的意图是,在id为#flash的div上执行slideUp动画,并在动画完成时删除元素。纯JS Snippet工作正常,但我不明白,为什么编译的CS不能完成它的工作
我根本不熟悉JavaScript或CoffeeScript,所以我会非常高兴这里提示。
答案 0 :(得分:3)
您的原始代码等同于CoffeeScript
$(document).ready ->
window.setTimeout (->
$('#flash').slideUp 'slow', (-> $(this).remove())
), 1000
相反,您已将1000
作为slideUp
函数的第三个参数。由于setTimeout
需要时间参数,因此没有任何反应。
请注意,我喜欢在setTimeout
周围创建一个包装函数,为了可读性而交换这两个参数:
window.delay = (ms, func) -> setTimeout func, ms
一旦定义了,你可以写
$(document).ready ->
delay 1000, -> $('#flash').slideUp 'slow', (-> $(this).remove())