Another discussion: How jquery writes plug-ins

Source: Internet
Author: User

Copyright Notice: Author original, reprint please indicate the source!

There are two ways to write plugins:

1. Class-level development plug-ins (1%)

2. Object-level development (99%)

Static development at the class level is the addition of static methods to jquery, three ways

1. Add a new global function

2. Using $.extend (obj)

3. Using namespaces

Class-level development plug-in (very little, 1%)

Examples of each:

1. Add global function jquery.myalert=function (str) {    alert (str) directly to Jquer;};/ /2. Use the Extend () method. Extend is a method provided by jquery that merges multiple objects together with the parameter Objectjquery.extend ({    myalert2:function (str1) {        alert (str1);    },    myalert3:function () {        alert (11111);    }}); /Be sure to note the differences in writing plug-in methods at two kinds of levels. 3. Use namespaces (if you are not using namespaces easily with the same name method in the other introduced JS libraries) jquery.yuqing={    myalert4:function (str) {        alert (str);    },    centerwindow:function (obj) {        obj.css ({            ' top ':($ (window). Height ()-obj.height ())/2,            ' left ':( $ (window). Width ()-obj.width ())/2        });        You must perform an operation that returns an object, or you cannot continue the chain operation downward.        return obj;    }};

Invocation part:

  Call the custom plug-in method  $ (' #btn '). Click (function () {      $.myalert (' I am calling the plugin popup warning box written by jquery ');      $.myalert2 (' I am calling the Extend () method of jquery to write the pop-up Warning box ');      $.myalert3 ();      $.YUQING.MYALERT4 ("Call the plugin method written using the namespace");  }); $.yuqing.centerwindow ($ (' #div1 ')). CSS (' background ', ' red ');

Note: jquery files are introduced together.

Object-level development plug-ins (common 99%)

jquery officially gives a set of object-level templates for developing plug-ins:

;(function ($) {    $.fn.plugin=function (options) {        var defaults={            //Various parameters, various properties        };
Options are merged into defaults, defaults inherits the various properties and methods on the options, assigns all the values to Endoptions var endoptions=$.extend (defaults, options); This.each (function () { //code to implement function });} ;}) (JQuery);

Template Highlights:

1. The function is put in the closure, the outside function will not call the inside parameters, more secure
2. Avoid unnecessary trouble by adding semicolons to the front

Give me a chestnut:

Requirement: Develop a plug-in that requires odd line color to be yellow, even if the row color is green, the row moved by the mouse becomes blue, and the color removed becomes the original

HTML Layout:

View Code

CSS Styles

View Code

jquery Calling Code:

$ (' #tab '). Table ({    evenrowclass: ' EvenRow1 ',    oddrowclass: ' OddRow1 ',    currowclass: ' CurRow1 ',    EventType1: ' click '});

jquery Plugin Code:

1;(function ($) {2 $.fn.table=function (options) {3 var defaults={4//Various parameters, various properties 5 Evenrowclass: ' Evenrow ', 6 oddrowclass: ' Oddrow ', 7 currowclass: ' Currow ', 8 eventType1: ' MouseOver ', 9 eventType2: ' mouseout '};11 var endoptions=$.extend (defaults,options ); This.each (function () {$ var _this = $ (this); _this.find (' Tr:even '). A Ddclass (Endoptions.evenrowclass); _this.find (' tr:odd '). addclass (Endoptions.oddrowclass);
18//mouse move in and out, but the actual development does not directly use MouseOver this method/*$ (this). Find (' tr '). MouseOver (function () {20 $ (this). addclass (Endoptions.currowclass)). Mouseout (function () {A $ (this). Removecla SS (Endoptions.currowclass); 23}); */24 25//The Bian () method is used in actual development to bind 26//Because Bind () Method binding is very flexible, events can be defined by themselves//mouseover mouseout ... The bottom of the event is implemented with BIND (), mouseout and so on are just shortcuts to _this.find (' tr '). Bind (Endoptions.eventtype1,function () {29 $ (this). addclass (Endoptions.currowclass); _this.find (' tr '). Bind (Endoptions.eventtype2,f Unction () {$ (this). Removeclass (Endoptions.currowclass);) (};36}) (J Query);

Plugin Comments:

15 rows: var _this = this; Variable storage, as many places use $ (this), so it is more convenient to store it as a variable, and it also improves operational efficiency.

The 19-23 rows are the same as the 28-33 line implementations, but it is recommended to use a 28-33-line notation, using bian () for event binding, because the use is very flexible.

Variable places, such as style names, are best written in defaults, allowing users to configure themselves.

Another object level implementation of jquery plug-in chestnuts (⊙o⊙) Oh!! Implement Tab Function ~ ~

HTML Layout

<div id= "tab" >    <ul id= "nav" >        <li class= "active" >HTML</li>        <li>css</ li>        <li>JAVASCRIPT</li>    </ul>    <div id= "cont" >        <div style= "Display: Block; " >HTML</div>        <div>CSS</div>        <div>JAVASCRIPT</div>    </div> </div>

CSS style:

* {    margin:0;    padding:0;} #nav li {    list-style:none;    Float:left;    height:25px;    line-height:25px;    border:1px solid #0000FF;    Border-bottom:none;    padding:5px;    margin:10px;    margin-bottom:0;} #cont Div {    width:210px;    height:150px;    border:1px solid #0000FF;    margin-left:10px;    Clear:both;    Display:none;}. Active {    background: #AFEEEE;}

Invoking the JS code

<script type= "Text/javascript" >    $ (' #tab '). tab ({        tabtype: ' MouseOver '    });</script>

Note: Don't forget to introduce the Jquery.js file first, and then introduce the plug-in Tab.js we wrote in order to correctly call the tab () method ...

Plugin Tab.js

;(function ($) {    $.fn.tab = function (options) {        var defaults = {            Tabactiveclass: ' Active ',            tabnav: ' #nav >li ',            tabcont: ' #cont >div ',            tabtype: ' click '        };        var endoptions = $.extend (defaults, options);        $ (this). each (function () {            var _this = $ (this);            _this.find (Endoptions.tabnav). bind (Endoptions.tabtype, function () {                $ (this). AddClass ( Endoptions.tabactiveclass). Siblings (). Removeclass (Endoptions.tabactiveclass);                var index = $ (this). index ();                _this.find (Endoptions.tabcont). EQ (index). Show (). siblings (). Hide ();});})    (JQuery);

This little chestnut and the last table plug-in chestnut similarity is very high, many times, to understand the meaning, in fact, the jquery extension is not difficult oh ~ ~

Another discussion: How jquery writes plug-ins

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.