jQuery插件通用写法

参考网址:http://www.cnblogs.com/wayou/p/jquery_plugin_tutorial.html
深入理解jQuery插件开发:http://blog.jobbole.com/30550/
 
完整插件demo:
/   **
 * 表格隔行变字体颜色和背景颜色,鼠标移入移出变字体颜色
 *
 * HTML页面调用方法:
 * $(function(){
 *     $("table").ChangeWordColor({
 *         oddWd:"blue"
 *     }).ChangeBgColor({
 *         oddBg:"purple"
 *     });
 *  })  
 *   /
 
;(function($){
    $.fn.extend({
        //变字体颜色
        "ChangeWordColor":function(options){ 
            options = $.extend({   //默认属性
                oddWd:"red",
                evenWd:"green",
                selectsWd:"yellow",
                noselectsWd:"#000"
            },options);   //如果你在调用的时候写了新的参数,就用你新的参数,如果没有写,就用默认的参数。
            return this.each(function(){   //return代表支持链式操作,可选
                var thisTable = $(this); 
                //添加奇偶行颜色 
                thisTable.find("tr:even").css("color",options.evenWd); 
                thisTable.find("tr:odd").css("color",options.oddWd); 
                //添加活动行颜色 
                thisTable.find("tr").on({
                    mouseover:function(){$(this).css("color",options.selectsWd);},
                    mouseout:function(){$(this).css("color",options.noselectsWd);}
                });
            });
        },
        //变背景颜色
        "ChangeBgColor":function(options){ 
            options = $.extend({
                oddBg:"pink",
                evenBg:"orange",
            },options);
            return this.each(function(){ 
                var thisTable = $(this); 
                //添加奇偶行背景颜色 
                thisTable.find("tr:even").css("background-color",options.evenBg); 
                thisTable.find("tr:odd").css("background-color",options.oddBg); 
            });
        },
    });
})(jQuery);
通过$.fn向jQuery添加操作DOM插件:
$.fn.disable = function(){
   return this.each(function(){
if(this.disabled != null)  this.disabled = true;
   });
}
通过$.extend()来扩展jQuery的静态方法:
$.extend({
    sayHello: function(name) {
        console.log('Hello,' + (name ? name : 'Dude') + '!');
    }
})
$.sayHello(); //调用
$.sayHello('Wayou'); //带参调用
 
补充:jQuery on()方法:
1.单事件操作:
$("body").on("click",function(){
$(this).css("background-color","red");
});
2.多个事件绑定同一个函数:
$("body").on("mouseover mouseout",function(){
$(this).toggleClass("intro");
});
3.多个事件绑定不同函数:
$("body").on({
mouseover:function(){$(this).css("background-color","red");},
mouseout:function(){$(this).css("background-color","blue");}
});
原文地址:https://www.cnblogs.com/gyx19930120/p/4419961.html