将嵌套函数调用到同一对象

时间:2014-02-07 08:16:12

标签: jquery plugins jquery-plugins

我正在开发一个插件,在向插件添加对象之后我想从外部调用一些事件到同一个对象,我该怎么做

(function ($, undefined) {

    jQuery.fn.pluginname = function (options) {
        var set = $.extend({
            opacity: 0.5             
        }, options);

        //if(options.type)

        var cdiv = this;
        cdiv.css("opacity",set.opacity);

        function callthis()
        {
            cdiv.css("display","none");
        }
    }
})(jQuery);


jQuery("#first").pluginname({opacity:0.5});

jQuery("#second").pluginname({opacity:0.5});

// call this function later

jQuery("#first").pluginname("callthis");

2 个答案:

答案 0 :(得分:0)

通常的方法是让你的插件接受“方法”作为字符串参数,例如:

jQuery("#first").pluginname("callThis");

在插件内部,您将该请求路由到该函数。

通常,您还希望将最初使用的选项存储在除关闭之外的其他位置; data对此很有用。

您通常使用"destroy"方法从元素中删除插件。

所以:

(function ($, undefined) {
    var methods = {
        init: function(options) {
            // Determine options
            var opts = $.extend({
                opacity: 0.5             
            }, options);

            // Remember them
            this.data("pluginname", opts);

            // Initial stuff
            this.css("opacity", opts.opacity);
        },

        callThis: function(opts) {
            // Use 'opts' if relevant
            this.css("display","none");
        },

        destroy: function(opts) {
            this.removeData("pluginame");
            this.css("display", "").css("opacity", "");
        }
    };

    jQuery.fn.pluginname = function (options) {
        var method, args;

        // Method?
        if (typeof options === "string") {
            // Yes, grab the name
            method = options;

            // And arguments (we copy the arguments, then
            // replace the first with our options)
            args = Array.prototype.slice.call(arguments, 0);

            // Get our options from setup call
            args[0] = this.data("pluginname");
            if (!args[0]) {
                // There was no setup call, do setup with defaults
                methods.init.call(this);
                args[0] = this.data("pluginname");
            }
        }
        else {
            // Not a method call, use init
            method = "init";
            args = [options];
        }

        // Do the call
        methods[method].apply(this, args);
    };
})(jQuery);

Live Example | Source

答案 1 :(得分:0)

试试这个:

(function ($, undefined) {

    jQuery.fn.pluginname = function (options) {
        var set = $.extend({
            opacity: 0.5             
        }, options);

        //if(options.type)
        if(typeof options == function){
        return function callthis()
        {
            cdiv.css("display","none");
        }
        } else{
        return function(){
        var cdiv = this;
        cdiv.css("opacity",set.opacity);
        }
        }


    }
})(jQuery);
相关问题