jQuery plugin - update settings after initialization

前端 未结 2 1505
小鲜肉
小鲜肉 2020-12-17 03:40

I have a jQuery plugin, and I want to be able to change options on the fly, like this example: $(\'.element\').pwstabs(\'options\',\'effect\',scale) or somethin

2条回答
  •  不思量自难忘°
    2020-12-17 04:26

    Try this pattern

    (function ($) {
        var defaults = {
            "text": "abcdefg",
        }
        , options = $.extend({}, defaults, options);
        $.fn.plugin = function (options) {
            var options = (function (opts, def) {
                var _opts = {};
                if (typeof opts[0] !== "object") {
                    _opts[opts[0]] = opts[1];
                };
                return opts.length === 0 
                       ? def 
                       : typeof opts[0] === "object" 
                         ? opts[0] : _opts
            }([].slice.call(arguments), defaults));
            return $(this).text(options.text)
        }
    }(jQuery));
    
    $(".results:eq(0)").plugin(); // return `defaults`
    $(".results:eq(1)").plugin({"text":"gfedcba"}); // return `options`
    $(".results:eq(2)").plugin("text", 123); // return `arguments` as `options`
    

        (function ($) {
            var defaults = {
                "text": "abcdefg",
            }
            , options = $.extend({}, defaults, options);
            $.fn.plugin = function (options) {
                var options = (function (opts, def) {
                    var _opts = {};
                    if (typeof opts[0] !== "object") {
                        _opts[opts[0]] = opts[1];
                    };
                    return opts.length === 0 
                           ? def 
                           : typeof opts[0] === "object" 
                             ? opts[0] : _opts
                }([].slice.call(arguments), defaults));
                return $(this).text(options.text)
            }
        }(jQuery));
        
        $(".results:eq(0)").plugin(); // return `defaults`
        $(".results:eq(1)").plugin({"text":"gfedcba"}); // return `options`
        $(".results:eq(2)").plugin("text", 123); // return `arguments` as `options`
    
    


提交回复
热议问题