Jen*_*sen 2 jquery this return-value jquery-plugins
我使用以下模式编写一个jquery插件,我希望bar
函数返回内部值,但似乎总是返回$(this)
.
代码有什么问题吗?
(function($){
var Foo = function(elements, options){
... ...
}
Foo.prototype = {
constructor: Foo,
bar: function(){
var value = ...
// do something here
return value;
},
}
$.fn.foo = function (option, kwargs){
return this.each(function(){
var $this = $(this),
data = $this.data('foo'),
options = typeof option == 'object' && option
if (!data) $this.data('foo', (data = new Foo(this, options)))
if (typeof option == 'string') return data[option](kwargs)
})
}
})(jQuery)
Run Code Online (Sandbox Code Playgroud)
不,代码是正确的.问题是它当前设置为总是返回一个jQuery选择器(返回值this.each
).要返回函数的结果,可以修改函数,$.fn.foo
如下所示:
$.fn.foo = function (option, kwargs){
var retval = null;
this.each(function(){
var $this = $(this),
data = $this.data('foo'),
options = typeof option == 'object' && option
if (!data) $this.data('foo', (data = new Foo(this, options)))
if (typeof option == 'string') {
retval = data[option](kwargs);
}
})
if (!retval) {
retval = this;
}
return retval;
}
Run Code Online (Sandbox Code Playgroud)