开发jQuery插件

来源:互联网 发布:唯品会淘宝天猫哪个好 编辑:程序博客网 时间:2024/06/18 06:23

开发jQuery插件一般有以下两种方式:

1.通过$.extend()来扩展jQuery2.通过$.fn 向jQuery添加新的方法

1.$.extend()
注意:这种方式无法利用jQuery强大的选择器带来的便利

$.extend({    sayHello: function(name) {        console.log('Hello,' + (name ? name : 'Dude') + '!');    }})$.sayHello(); //调用$.sayHello('Wayou'); //带参调用

2.$.fn

;(function($, window, document,undefined) {    //定义cssTree的构造函数    var cssTree = function(ele, opt) {        this.$element = ele,        this.defaults = {            'color': 'red',            'fontSize': '12px',            'textDecoration': 'none'        },        this.options = $.extend({}, this.defaults, opt)    }    //定义cssTree的方法    cssTree.prototype = {        cssTreeInit: function() {            return this.$element.css({                'color': this.options.color,                'fontSize': this.options.fontSize,                'textDecoration': this.options.textDecoration            });        }    }    //在插件中使用cssTree对象    $.fn.cssTreeInit = function(options) {        //创建cssTree的实体        var csstree = new cssTree(this, options);        //调用其方法        return csstree.cssTreeInit();    }})(jQuery, window, document);

使用方法:

 $("#box").cssTreeInit({         "width":'100%',       //宽高不指定的话,宽度默认是父元素的100%,高度自动         "height":"500px"                            });
原创粉丝点击