Way to execute jQuery member functions inside setT

2019-04-08 17:07发布

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);

What I've tried:

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?

1条回答
叛逆
2楼-- · 2019-04-08 17:19

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:

Function.bind

Cross Browser Alternative for this:

$.proxy

Ex:

var $elem = $('#element');
setTimeout($elem.hide.bind($elem),3000);

or

setTimeout($.proxy($elem.hide, $elem),3000);

or

setTimeout($.fn.hide.bind($elem),3000); //setTimeout($.proxy($.fn.hide, $elem),3000);

Fiddle

查看更多
登录 后发表回答