Way to execute jQuery member functions inside setTimeout without closure?

谁说我不能喝 提交于 2019-12-21 14:51:30

问题


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:


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



来源:https://stackoverflow.com/questions/20221163/way-to-execute-jquery-member-functions-inside-settimeout-without-closure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!