问题描述
我试图按照以下方式做点什么:
I was trying to do something along these lines:
setTimeout($('#element').hide,3000);
看起来很简单,但它被。我想找到一种方法来将实际函数作为参数传递,而不将其包装在另一个函数中,例如我不想这样做:
which seems simple enough, but it is crippled by the "this" problem. I want to find a way to just pass the actual function as a parameter, without wrapping it in another function, e.g. I do not want to do this:
setTimeout(function(){$('#element').hide();},3000);
我尝试过:
setTimeout($('#element').hide,3000);
setTimeout($('#element').hide.apply(document),3000); /* jQuery docs say that document is the default context */
setTimeout($('#element',document).hide,3000);
setTimeout($(document).find('#element').hide,3000);
setTimeout($(window).find('#element').hide,3000);
setTimeout($.proxy($('#element').hide,document),3000); /* I know this returns a function, which I don't want, but I have tried it */
setTimeout(($('#element').hide()),3000); /* functional expression */
我正在寻找解决这个问题的方法,但我不喜欢我想把它包装在另一个函数中。代码行越少越好。我知道为什么这不能按预期工作,但我如何解决它而不将其包装在闭包中?
I'm looking for the way to remedy this problem, but I don't want to wrap it in another function. The less lines of code, the better. I know WHY this isn't working as expected, but HOW can I fix it without wrapping it in a closure?
推荐答案
你可以通过将方法的上下文与元素本身绑定来实现这种方式,这样在jquery中隐藏方法这个
将指向jquery对象而不是全局上下文。您可以使用以下方法创建绑定函数:
You can do this way by binding the context of the method with the element itself so that in jquery hide method this
will point to jquery object and not global context. You can create bound functions using:
跨浏览器替代方案:
Ex:
var $elem = $('#element');
setTimeout($elem.hide.bind($elem),3000);
或
setTimeout($.proxy($elem.hide, $elem),3000);
或
setTimeout($.fn.hide.bind($elem),3000); //setTimeout($.proxy($.fn.hide, $elem),3000);
Fiddle
这篇关于在没有闭包的情况下在setTimeout中执行jQuery成员函数的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!