setTimeout 在 jQuery 插件中不起作用
setTimeout not working inside jQuery plugin
我的 jQuery 插件中有一些附加到 keyup 事件的行为。除了在超时立即执行后应该触发的功能外,一切正常。
//attach keyup event for the searchbox
self.data('gallery_searchTimeout',null); //to enable a delay on the keypress search event
$(self).find('.gallery-search').keyup(function(){
var needle = 'look for me';
var delay = 2000;
//if a timer is already set, clear it in favor of our new timer
if (self.data('gallery_searchTimeout') != undefined) clearTimeout(self.data('gallery_searchTimeout'));
self.data('gallery_searchTimeout', setTimeout((self.data('search')(self,needle)), delay) );
});
var search = function(self,needle) {
console.log('search called with needle: '+needle);
};
self.data('search',search);
将函数传递给 setTimeout
而不是调用它。
改变
self.data('gallery_searchTimeout', setTimeout((self.data('search')(self,needle)), delay) );
到
self.data('gallery_searchTimeout', setTimeout(self.data('search').bind(null,self,needle), delay) );
或
self.data('gallery_searchTimeout', setTimeout(function(){
self.data('search')(self,needle);
}, delay) );
我的 jQuery 插件中有一些附加到 keyup 事件的行为。除了在超时立即执行后应该触发的功能外,一切正常。
//attach keyup event for the searchbox
self.data('gallery_searchTimeout',null); //to enable a delay on the keypress search event
$(self).find('.gallery-search').keyup(function(){
var needle = 'look for me';
var delay = 2000;
//if a timer is already set, clear it in favor of our new timer
if (self.data('gallery_searchTimeout') != undefined) clearTimeout(self.data('gallery_searchTimeout'));
self.data('gallery_searchTimeout', setTimeout((self.data('search')(self,needle)), delay) );
});
var search = function(self,needle) {
console.log('search called with needle: '+needle);
};
self.data('search',search);
将函数传递给 setTimeout
而不是调用它。
改变
self.data('gallery_searchTimeout', setTimeout((self.data('search')(self,needle)), delay) );
到
self.data('gallery_searchTimeout', setTimeout(self.data('search').bind(null,self,needle), delay) );
或
self.data('gallery_searchTimeout', setTimeout(function(){
self.data('search')(self,needle);
}, delay) );