zoukankan      html  css  js  c++  java
  • 如何写一个jquery插件

          本文总结整理一下如何写一个jquery插件?虽然现今各种mvvm框架异常火爆,但是jquery这个陪伴我们成长,给我们带来很多帮助的优秀的库不应该被我们抛弃,写此文章,作为对以往欠下的笔记的补充,以及对jquery的重温。

           写jquery插件有三种方法:

           1.使用$.extend()来拓展jquery;

           2.使用$.fn来给jquery添加新的方法;

           3.使用$.widget()应用jquery UI的部件工厂方式创建。

            方法一:      

    $.extend({
            'sayHello':function(msg){
                 console.log(msg);
            },
            $(function(){
              $.sayHello('Hello jQuery!!!');//Hello jQuery!!!
            });
    });
    

        方法二:

            

     //方法二(基本):jQuery.fn = jQuery.prototype = {
    	 //}
         $.fn.myplugin = function(){
             this.css('background','red');
         }
    

      

     //方法二(传参):
         $.fn.myPlugin  = function(opt){
             var defaults = {
             	 'bgc':'red',
             	 'fontSize':'12px'
             };
             var settings = $.extend({},defaults,opt);
             debugger;
             this.css({
             	 'background':settings.bgc,
             	 'fontSize':settings.fontSize
             });
         }
    

      

    //继续升级方法二,改造成面向对象的形式来定义插件,提升插件的可读性可维护性,
         ;(function($,window,document,undefined){
    		var Beautifier = function(ele,opts){
    		 this.$element = $(ele);
    		 this.defaults = {
    		     'bgc':'red',
    		 	 'fontSize':'12px'
    		 }
    		 this.settings = $.extend({},this.defaults,opts);
    		};
    		Beautifier.prototype = {
    		 'construct':Beautifier,
    		  'bueatify':function(){
    		  	  return this.$element.css({
    		  	  	   'background':this.settings.bgc,
    		 	        'fontSize':this.settings.fontSize
    		  	  })
    		  }
    		}
    		$.fn.myplugin2 = function(opts){
    			var bt = new Beautifier(this,opts);
    			return bt.bueatify();
    		}
         })(jQuery,window,document);
    

      

     //调用
         $(function(){
            $("a").myplugin2({
            	'bgc':'red',
            	'fontSize':'50px'
            });
         });
    

      执行结果:

         

         方法三:这个方法用的较少,暂时不做研究讲解。

           

           

          

  • 相关阅读:
    Codeforces 1485C Floor and Mod (枚举)
    CodeForces 1195D Submarine in the Rybinsk Sea (算贡献)
    CodeForces 1195C Basketball Exercise (线性DP)
    2021年初寒假训练第24场 B. 庆功会(搜索)
    任务分配(dp)
    开发工具的异常现象
    Telink MESH SDK 如何使用PWM
    Telink BLE MESH PWM波的小结
    [LeetCode] 1586. Binary Search Tree Iterator II
    [LeetCode] 1288. Remove Covered Intervals
  • 原文地址:https://www.cnblogs.com/xinggood/p/6708969.html
Copyright © 2011-2022 走看看