Two ways to develop a plug-in for jquery

Source: Internet
Author: User
Tags rtrim

Recently quite a lot of people write jquery, are about the expansion of jquery, the use of more than speaking, but about a detailed basis of the process is less, do the web development of the basic will use jquery, I based on the use of jquery to talk about plug-in development. jquery plug-in development two ways: one is the way to develop plug-ins, jquery add new global functions (jquery's global function is a function of the jquery namespace), if you consider jquery as a class, it is equivalent to the jquery class itself to add methods. The second is the way the object is extended to develop plug-ins, that is, the JQuery object Add method.

Plug-in for class extensions

The most straightforward understanding of plug-in development for class extensions is to add class methods to the jquery class, which can be understood as adding static methods. The typical example is $. The AJAX () function, which defines the function in the jquery namespace. Plug-in development for class extensions can be extended in the following ways:

1. Add a global function

123 $.ltrim = function( str ) {       returnstr.replace( /^\s+/, "");   };

Invocation mode

12 varstr="  去除左空格 ";console.log("去除前:"+str.length+"去除后:"+$.ltrim(str).length);

2. Add multiple global functions

1234567 $.ltrim = function( str ) {    returnstr.replace( /^\s+/, "" );}; $.rtrim = function( str ) {    return str.replace( /\s+$/, "");};

The above kind if you write the global function is very good, if more than the use of $.extend (object) is recommended to use

12345678 $.extend({    ltrim:function( str ) {      returnstr.replace( /^\s+/, "" );  },  rtrim:function( str ) {      return str.replace( /\s+$/, "");  }  });

3. Stand-alone namespaces

Although in the jquery namespace, we prohibit the use of a large number of JavaScript function names and variable names. However, it is still inevitable that some functions or variable names will conflict with other jquery plugins, so we are accustomed to encapsulating some methods into another custom namespace.

12345678 $.myPlugin={      ltrim:function( str ) {       returnstr.replace( /^\s+/, "" );   },   rtrim:function( str ) {       return str.replace( /\s+$/, "");   }};

With a separate plug-in name, you can avoid conflicts of functions within namespaces by invoking the following methods:

12 varstr="  去除左空格 ";console.log("调用前:"+str.length+"调用后:"+$.myPlugin.ltrim(str).length);
plug-in for object extensions

1. Add an object extension method

123456   $.fn.changeColor= function() {    this.css( "color""red");};   $.fn.changeFont= function() {    this.css( "font-size""24px");};

Call Mode:

123 $(function() {   $("a").showColor();<br>       $("div").changeFont();});

2. Add multiple Object extension methods

12345678   (function($){      $.fn.changeColor= function() {    this.css( "color""red");};   $.fn.changeFont=function() {    this.css( "font-size""24px");};  })(jQuery);

Compatible notation (prevents the previous function from missing;):

12345678 ;(function($){      $.fn.changeColor= function() {    this.css( "color""red");};   $.fn.changeFont=function() {    this.css( "font-size""24px");};  })(jQuery);

A jquery function is defined above, and the parameter is $, and after the function definition is complete, the jquery argument is passed in. Call execution immediately. The advantage of this is that when we write a jquery plugin, we can also use this alias, without causing a conflict with prototype.

3. Using $.fn.extend (object)

Off-topic, view the jquery source code (version 1.11.1) to see:

123456 jQuery.fn = jQuery.prototype = {    // The current version of jQuery being used    jquery: version,    constructor: jQuery,......................    },

jquery is a well-encapsulated class, such as a statement $ ("a") that generates an instance of the jquery class. JQuery.fn.extend (object) is actually an extension to the Jquery.prototype, which is to add a "member function" to the jquery class. An instance of the jquery class can use this "member function".

12345678   $.fn.extend({  changeColor:function() {  this.css( "color""red");},changeFont:function() {    this.css( "font-size""24px");}});

The basic usage of object extensions is described below, and a simple function similar to code highlighting is developed below:

123456789101112131415161718192021222324252627282930313233 (function($) {   $.fn.highlight = function(options) {     //插件参数的可控制性,外界可以修改默认参数     vardefaults=$.extend($.fn.highlight.defaults, options );     //遍历函数,然后根据参数改变样式   returnthis.each(function() {        varelem = $( this);        varmarkup = elem.html();        markup = $.fn.highlight.format( markup );        elem.html(markup);        elem.css({            color: defaults.color,            fontSize:defaults.fontSize,            backgroundColor: defaults.backgroundColor        });    });};//参数默认值$.fn.highlight.defaults={            color: "#556b2f",            backgroundColor:"white",            fontSize: "48px"        };//格式化字体$.fn.highlight.format = function( txt ) {    return"<strong>"+ txt + "</strong>";};})(jQuery);      $(function() {        //调用插件        $("a").highlight({color:"red",fontSize:"24px"});    });
Summary

jquery The use of these two plug-in development, depending on the development process of the specific situation, the first kind of extension method is similar to C # Add a static method, the second object extension is based on their actual business and determined that your site in some places commonly used functions can certainly be written in a plug-in, For example, the view of the picture, the click of the sidebar, sometimes you can also study the online other people write plug-ins, you can learn a lot of things.

Two ways to develop a plug-in for jquery

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.