JQuery插件的一般写法

(function($){
    //扩展这个方法到jQuery
    let Plugin = function(){

    }
    Plugin.prototype = {};
    $.fn.extend({
        //插件名字
        pluginname: function(options){
            let args = [].slice.call(arguments, 1);
            //遍历匹配元素的集合
            return this.each(function(){
                let ui = $._data(this, pluginname);
                if (!ui) {
                    let opts = $.extend(true, {}, $.fn.pluginname.defaults, typeof options === "object" ? options : {});
                    ui = new Plugin(opts, this);
                    $._data(this, pluginname, ui);
                }
                if (typeof options === "string" && typeof ui[options] === "function") {
                    ui[options].apply(ui, args);//执行插件的方法
                }
            });
        }
    });

    //默认配置
    $.fn.pluginname.defaults = {};

})(jQuery);

猜你喜欢

转载自www.cnblogs.com/KruceCoder/p/10231291.html
今日推荐