我该如何将$(this)的上下文传递给插件?
目前,我有一个插件(代码如下所示)
(function($) {
$.fn.slides={
slideIn:function(){
$(this).fadeIn().slideDown();
},
slideOut:function(){
$(this).fadeOut().slideUp();
}
}
})(jQuery);
当插件通过以下方式被调用时:
$('h1').click(function(){
$(this).slides.slideOut();
});
我遇到了一个错误。
Uncaught TypeError: Cannot read property 'defaultView' of undefined
由于上下文未被正确传递给插件的 slideOut() 方法,因此出现了这个问题。也就是说,slideOut 的上下文是 $.fn.slides 对象。
除了使用 .call() 来传递上下文之外,例如:
$('h1').click(function(){
$(this).slides.slideOut.call(this);
});
有没有其他方法可以正确地将this上下文传递给slideOut(),或者以任何方式构建我的插件,使我可以通过
$('h1').click(function(){
$(this).slides.slideOut();
});
?
Thanks!