我正在尝试构建一个jQuery插件,使用名称间距按照这里的方向: http://docs.jquery.com/Plugins/Authoring#Namespacing
现在我遇到了一个问题,我的插件需要使用setTimeout来触发其中一个方法,
var jScrollerMethods = {
ready:function(){
return this.each(function(){
var self = this,
$this = $(this),
data = $this.data('jScroller');
settings.timeoutHandle = setTimeout(function(){
if(settings.direction = "left"){
this.moveLeft();
}else if(settings.direction = "right"){
this.moveRight();
}
}, settings.time);
$this.data('jScroller', {
settings: settings,
element: this
});
});
}
$.fn.jScroller = function(call){
if ( jScrollerMethods[call] ) {
return jScrollerMethods[call].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof call === 'object' || ! call ) {
if (call) { $.extend(settings, call); }
return jScrollerMethods.init.apply( this, call );
} else {
$.error( 'Method ' + call + ' does not exist on jQuery.jScroller' );
}
}
但是因为我会发生setTimeout是从Window而不是插件对象触发的,并且我希望插件每页可以多次使用所以我不能只将当前对象保存到窗口怎么能我实现了这个目标吗?
答案 0 :(得分:0)
我发现在this
之外使用return this.each
会给你精确的选择结果
所以通过一些工作我已经设法做到了,
var jScrollerMethods = {
ready:function(){
selector = this;
return this.each(function(){
var self = this,
$this = $(this),
data = $this.data('jScroller');
settings.timeoutHandle = setTimeout(function(){
if(settings.direction = "left"){
selector.jScroller("moveLeft");
}else if(settings.direction = "right"){
selector.jScroller("moveRight");
}
}, settings.time);
$this.data('jScroller', {
settings: settings,
element: this
});
});
}
$.fn.jScroller = function(call){
if ( jScrollerMethods[call] ) {
return jScrollerMethods[call].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof call === 'object' || ! call ) {
if (call) { $.extend(settings, call); }
return jScrollerMethods.init.apply( this, call );
} else {
$.error( 'Method ' + call + ' does not exist on jQuery.jScroller' );
}
}