大家好。
我正在尝试按照我在http://docs.jquery.com/Plugins/Authoring中找到的步骤开发一个Jquery插件,我似乎在传递给插件的选项中到达调用者对象(“this
”变量)时遇到了问题。这是一个插件,我只想用它来制作一个按钮具有“闪烁”效果。
我希望能够将这些函数传递给“show / hide”(或链接闪烁,闪烁,如果你愿意)作为插件的一个选项。假设用户希望通过每1000毫秒隐藏/显示整个按钮来实现“闪烁”效果。然后我希望选项类似于:
$("#bttnOk").myBlinker ({
blinkHide: function(){$(this).hide();},
blinkShow: function(){ $(this).show();},
interval:1000
});
// … //
// And to make it actually blink:
$("#bttnOk").myBlinker ("blink");
或者假设用户想要每隔200毫秒上下移动按钮来应用内联css sytle。那么选项就像:
$("#bttnOk").myBlinker ({
blinkHide: function(){$(this).css(“margin-top: 10px”);},
blinkShow: function(){ $(this).css(“margin-top: 0px”);},
interval:200
});
问题是,当我在选项中时,我似乎失去了对“$(this)”的引用。当插件到达blinkHide/blinkShow
函数时,“this
”是整个DOM窗口,而不是我的“myBlinker”插件附加到的按钮$(“#bttnOk”)。
这是我试图编写的第一个Jquery插件,所以我甚至不确定是否有办法实现我想要做的事情。
我的插件代码遵循以下结构:
(function($){
var defaultOptions = {
interval: 500
}
var methods = {
init : function( options ) {
return this.each(function(){
this.options = {}
$.extend(this.options, defaultOptions, options);
var $this = $(this);
var data = $this.data('myBlinker');
// If the plugin hasn't been initialized yet
if ( ! data ) {
$this.data('myBlinker', {
on : true
});
}
});
},
destroy : function( ) { // Some code here},
blink: function ( ){
console.log("Blinking!. This: " + this);
var current = 0;
var button=this.get(0);
setInterval(function() {
if (current == 0){
button.options["blinkShow"].call(this);
current=1;
} else {
button.options["blinkHide"].call(this);
current=0;
}
}, button.options["interval"]);
}
};
$.fn. myBlinker = function( method ) {
// Method calling logic
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.myBlinker ' );
return null;
}
};
})(jQuery);
任何想法,更正,链接或提示将不胜感激。
谢谢。
答案 0 :(得分:4)
在setInterval
函数中,this
是全局对象,而不是像闪烁函数中的当前元素DOMElement。
解决方法是保存this
的引用并在setInterval中使用此保存的引用:
blink: function ( ){
// save a reference of 'this'
var that = this;
setInterval(function() {
// use the saved reference instead of 'this'
button.options["blinkShow"].call(that);
}, button.options["interval"]);
}
<强> DEMO 强>