Sharp jquery-7--Writing plug-in basics

Source: Internet
Author: User
Tags define local

Basic points of the plugin:

1. Name recommendation: jquery. [Plugin name].js, avoid confusion with other JS library plugins.

2. Object method attached to: Jquery.fn, global function attached to: JQuery object itself.

3. Inside the plug-in, this points to the JQuery object currently acquired through the selector, not a DOM object.

4. If the selector gets multiple elements, it can be traversed by This.each.

5. Plug-ins should return jquery objects for easy chain operation.

6. Avoid using the $ alias inside the plugin, which should be expressed in full jquery. Closures can be used to avoid this problem.

// for better compatibility, add a semicolon to prevent compression when the other JS code does not have a semicolon ;(function($) {   // here will be the parameters of the anonymous function passed in    // write Code }) (jQuery);   // jquery is passed in as an argument and can be used within an anonymous function.

The closure in the plugin understands:

;(function($){    varfoo = 1;//define local variables, only the anonymous function can be accessed internally    varBar =function(){        /*The function inside the anonymous function can access Foo, even if the bar function is called outside of the anonymous function, it can be accessed inside bar (), but it cannot be accessed directly outside of the anonymous function .*/    }        /*the functions below allow the function bar () inside the anonymous function to escape to the globally accessible range so that the internally defined function bar () can be accessed outside of the anonymous function, and the internal function bar () can also access the Foo variable .*/    $. BAR=bar ();}) (jQuery);

Sharp jquery-7--Writing plug-in basics

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.