jquery 插件开发

插件开发两种方式:
第一种:
$.extend({
    sayHello: function(name) {
        console.log('Hello,' + (name ? name : 'Dude') + '!');
    }
})
$.sayHello(); //调用
$.sayHello('Wayou'); //带参调用

第二种:
插件统一格式:
;(function($,window,document,undefined){//我们的代码。。//blah blah blah...})(jQuery,window,document);

最优写法:
;(function($, window, document,undefined) {

    //定义Beautifier的构造函数

    var Beautifier = function(ele, opt) {

        this.$element = ele,

        this.defaults = {

            'color': 'red',

            'fontSize': '12px',

            'textDecoration': 'none'

        },

        this.options = $.extend({}, this.defaults, opt)

    }

    //定义Beautifier的方法

    Beautifier.prototype = {

        beautify: function() {

            return this.$element.css({

                'color': this.options.color,

                'fontSize': this.options.fontSize,

                'textDecoration': this.options.textDecoration

            });

        }

    }

    //在插件中使用Beautifier对象

    $.fn.myPlugin = function(options) {

        //创建Beautifier的实体

        var beautifier = new Beautifier(this, options);

        //调用其方法

        return beautifier.beautify();

    }

})(jQuery, window, document);

//调用示例:
$("#id").myPlugin({color:color;fontSize:fontSize});

猜你喜欢

转载自blog.csdn.net/fzy629442466/article/details/84786011