自定义jquery插件

开发自定义Jquery插件

这几年随着各种前端框架的出现,操作DOM被更多的封装起来,有些项目你甚至可以完全抛开jquery进行开发,但不可否认的是,jquery多年来作为前端工程师的必备基本功夫有其不可替代的作用,即使你不用jquery,你也应该掌握他:

  • 大多数项目依然在采用jquery,虽然不作为框架,但作为操作DOM的库文件用;
  • 编写小网站依然是不错的选择,尤其是数不清的优秀插件能为你所用,他能单独为你撑起一片天;
  • jquery的编程思想,是理解javascript的很好的路子;

Begin(三种方式)

1. 构建js闭包

;(function($,window,document,undefined){

    'use strict';

    $('#app').html('hello world');

})(jQuery,window,document)

注意事项:

  • 1.1' ; '的使用,放只前一个函数末尾没';',导致js解析错误;

      var func = function{}
    
      (function($,window,document){
    
          'use strict';
    
          $('#app').html('hello world');
    
      })(jQuery,window,document)

控制台报错Uncaught SyntaxError: Unexpected token {

  • 1.2 jquery,window,document放入局部作用域中,据说可以加快速度,未测试出来,聊胜于无嘛,加上得了,undefined是为了...还没弄清,应该是变量污染。

  • 1.3 'use strict';采用严格模式,编写更规范化,将来向ES6容易过渡。

2. jquery插件模式(方式一)

;(function($,window,document){

    'use strict';

    $.fn.myPlugin = function(){
        return($(this).html('hello world'))
    }

})(jQuery,window,document)

//html code

<div id="app"></div>

...

<script type="text/javascript">
    $('#app').myPlugin();
</script>

执行后DIV中会加入'hello world'.

jquery.fn 即 jquery.prototype

3. 对选中的元素遍历,jquery选择器的牛逼之处

$.fn.myPlugin = function(){

    return this.each(function(){
        var $this = $(this);
        $this.html('hello world');
    })

}

//html code

<div class="app"></div>
<div class="app"></div>

<script type="text/javascript">
    $('.app').myPlugin();
</script>

4. 默认属性/方法保护

var defaults = {
    width:100,
    height:100
}

var defaultsFunc = {
    getValue:function(ele,param){},
    setValue:function(ele,param){}
}

var methods = {
    'init':function(option){
        option = $.extend({},defaults,option);
        return this.each(function(){
            var $this = $(this);
            $this.html('hello world');
        })
    },
    'destroy':function(){}
}

$.fn.myPlugin = function(){
    return methods.init.apply(this);
}

通过apply隐藏内部结构,通过$.extend来合并默认配置和用户自定义配置,避免多个实例对默认属性造成变化

5.对用户输入进行判断

用户输入的可能为多种类型,其他输入默认为非法输入,抛出异常:

$(ele).myPlugin(); //按照默认配置初始化
$(ele).myPlugin(string); //调用方法
$(ele).myPlugin(object); //按照自定义配置初始化


$.fn.myPlugin = function(){
    var args = arguments[0];
    if(!args){
        return methods.init.apply(this,arguments);
    }else{
        if(typeof(args) === 'object'){
            return methods.init.apply(this,arguments);
        }else if(typeof(args) === 'string'){
            if(methods[args]){
                return methods[args].apply(this,arguments);
            }else{
                throw new Error(args + 'is not a function of this plugin');
            }
        }else{
            throw new Error('unvaliabled param');
        }
    }
}

至此,一个插件的基本功能就具备了,接下来看看插件的其他知识.

6. 对jquery的方法进行拓展

//公有方法,外部能进行修改,可用于对插件进行拓展

$.fn.sayHello = function(){
    return {self:'self'}
}

or

$.fn.extend({
    sayHello: function(){
        return {self:'self'};
    }
})

//私有方法,只有插件内部进行调用

function func(){...}

or

var func = function(){...}

7.定义插件的另一种方式(方式二)

//默认参数
var defaluts = {
    foreground: 'red',
    background: 'yellow'
};

$.fn.extend({
    "highLight": function (options) {
        //检测用户传进来的参数是否合法
        if (!isValid(options))
            return this;
        var opts = $.extend({}, defaluts, options); 
        return this.each(function () {  
            var $this = $(this); 
        });

    }
});

8.还有一种类似方式(方式三)

//默认参数
var defaluts = {};

var highLight = function(ele,options){
    $(ele).html(options.value);
}

$.fn.selfHighLight = function(args){
    return this.each(function(){
        var hL = new highLight(this,args);
    })
}

9.通过$.widget()应用jQuery UI部件工场方法创建(很少用到jquery UI,没有尝试过,日后用到再实验吧)

猜你喜欢

转载自www.cnblogs.com/wuchenfei/p/9823660.html