Ken*_* .J 5 javascript jquery plugins jquery-plugins
我如何将$(this)的上下文传递给插件?
目前,我有一个插件(代码如下所示)
(function($) {
$.fn.slides={
slideIn:function(){
$(this).fadeIn().slideDown();
},
slideOut:function(){
$(this).fadeOut().slideUp();
}
}
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
当插件被调用时
$('h1').click(function(){
$(this).slides.slideOut();
});
Run Code Online (Sandbox Code Playgroud)
我收到一个错误
Uncaught TypeError: Cannot read property 'defaultView' of undefined
Run Code Online (Sandbox Code Playgroud)
因为这个上下文没有正确传递给插件的slideOut()方法.就像slideOut这个上下文是对象$ .fn.slides的上下文.
除了使用.call()传递上下文,即
$('h1').click(function(){
$(this).slides.slideOut.call(this);
});
Run Code Online (Sandbox Code Playgroud)
有没有其他方法可以正确地将此上下文传递给slideOut(),或者无论如何构造我的插件,以便我可以通过方法调用方法slideOut()
$('h1').click(function(){
$(this).slides.slideOut();
});
Run Code Online (Sandbox Code Playgroud)
?
谢谢!
像这样的东西看起来更像是一个 jQuery 插件:
(function ($) {
$.fn.slides = function(method) {
var methods = {
slideIn: function () {
$(this).fadeIn().slideDown();
},
slideOut: function () {
$(this).fadeOut().slideUp();
}
};
return this.each(function() {
methods[method].call(this);
});
};
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
用法:
$('h1').click(function() {
$(this).slides('slideOut');
});
Run Code Online (Sandbox Code Playgroud)
另请注意,jQuery 插件应返回 jQuery 实例集合以使可链接成为可能。