如何让jQuery插件函数返回内在价值

时间:2012-05-06 03:03:04

标签: jquery jquery-plugins this return-value

我使用以下模式编写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)

2 个答案:

答案 0 :(得分:5)

不,代码是正确的。问题是它当前设置为始终返回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;
}

答案 1 :(得分:1)

在外部函数中,你写了return this.each(...);`。

this.each总是返回你调用它的jQuery对象(用于链接);它会忽略您传递回调的返回值。

如果要从回调中返回值,请将该值放入变量中,然后在调用each后返回变量。 (这将起作用,因为each不是异步的。) 如果在具有两个元素的jQuery对象上调用方法,则需要弄清楚该怎么做;你可能想完全摆脱each电话。