【发布时间】:2011-07-08 23:40:08
【问题描述】:
类似...
$('.foo').live 'click', ->
setTimeout (()->$(this).parent().hide()), 5000
感谢您的帮助!
【问题讨论】:
标签: javascript jquery coffeescript
类似...
$('.foo').live 'click', ->
setTimeout (()->$(this).parent().hide()), 5000
感谢您的帮助!
【问题讨论】:
标签: javascript jquery coffeescript
James 已正确诊断出问题:当您将函数传递给 setTimeout 时,它会在 window 上下文中调用(就像您将 func 称为 func() 一样)。有两个很好的解决方案:
1) (最快) 将细箭头->改为粗箭头=>,将函数绑定到当前上下文,保证函数内this具有相同的值作为this 在它之外。那么你的代码就是
$('.foo').live 'click', ->
setTimeout (=> $(this).parent().hide()), 5000
2) (最有效) 只需在您传递给setTimeout 的函数之外捕获this 或$(this) 的值。与绑定函数相比,这具有更少的开销。那么你的代码就是
$('.foo').live 'click', ->
$this = $(this)
setTimeout (-> $this.parent().hide()), 5000
我发现自己经常在回调顶部写$this = $(this)。这是一个非常有用的习语,可以在确保流畅性能的同时为您省去很多麻烦。
【讨论】:
setTimeout 中的 this 将是 window 或未定义。在这种情况下,您最好使用匿名函数包装来关闭 this,或者使用 bind(this) 为函数绑定 this 对象
setTimeout((function() { return function() { $(this).parent().hide(); } })(), 5000);
或
var func = function() { $(this).parent().hide(); };
setTimeout(func.bind(this), 5000);
(我不太了解coffeescript,所以希望这是正确的JS等价物)
顺便说一句,jquery 没有像这样延迟动画的功能吗?
【讨论】:
$(this).parent().delay(5000).hide(0) 需要超时。再次感谢
setTimeout (=> $(this).parent().hide()), 5000,而不是 func.bind(this)(并非所有浏览器都支持)。这负责将函数绑定到当前上下文,它甚至可以在 IE6 中使用。
CoffeeScript 具有“立即调用传递的函数”的“do”关键字。它应该在这里有所帮助。
$('.foo').live 'click', ->
foo = $(this)
do foo ->
setTimeout (()->foo.parent().hide()), 5000
【讨论】:
do foo ->在这种情况下是多余的(只要foo的作用域是事件处理程序)。这是最有效的方法。在事件处理程序的顶部写入$this = $(this),然后在整个过程中使用$this。
$(this) 作用于函数。因此$(this) 这里没有指定$('.foo') 对象。您首先必须将该对象缓存在某个变量中,然后将该变量传递给您的 setTimeout 函数。
类似:
var foo = $('.foo');
setTimeout(foot.parent().hide(), 5000);
【讨论】: