gpt4 book ai didi

javascript - 将此上下文传递给插件

转载 作者:搜寻专家 更新时间:2023-11-01 04:17:07 26 4
gpt4 key购买 nike

我如何将 $(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

因为 this 的上下文没有正确传递给插件的 slideOut() 方法。即 slideOut 的 this 上下文是对象 $.fn.slides 的上下文。

除了使用 .call() 传递上下文,即

$('h1').click(function(){
$(this).slides.slideOut.call(this);
});

是否有任何其他方法可以将 this 上下文正确传递给 slideOut(),或者构造我的插件以便我可以通过以下方式调用方法 slideOut()

 $('h1').click(function(){
$(this).slides.slideOut();
});

?

谢谢!

最佳答案

像这样的东西看起来更像是一个 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);

用法:

$('h1').click(function() {
$(this).slides('slideOut');
});

另请注意,jQuery 插件应返回一个 jQuery 实例集合以实现可链接。

演示:http://jsfiddle.net/cC8fF/

关于javascript - 将此上下文传递给插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23147352/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com