Learn jquery with me. Plugin Development _jquery

Source: Internet
Author: User
While visiting the CodeProject website, I suddenly saw an article: how to write plugin in Jquery.
If you are good to E-wen, you can see the connection above.
Now I write this article with the above website and the idea of combining myself. Hope to get the support and understanding of Daniel ... Big Bird flew by ... Welcome to the photo outfit.
Source:

"1" How to write plugin in Jquery.

"2" sharp jquery Book

"3" Rascallysnake jquery.extend () detailed
I. Introduction
The purpose of the plug-in is to encapsulate an existing set of methods or functions so that they can be reused elsewhere to facilitate later maintenance.
In addition to providing a simple and efficient way to manage elements and scripts, jquery also provides an exception mechanism: adding its own methods and additional functionality to the core modules. With this mechanism, jquery allows us to create our own plug-ins that improve our efficiency in the development process.

1.1JQuery plugins are divided into 3 types:
(1) Plug-ins that encapsulate object methods (i.e. object-level development)
This type of plug-in is what we need to talk about today.
(2) Plug-ins that encapsulate global functions (class level development)
This means that you can add a separate function to the jquery namespace.
To add a global function, we just need to define the following:
Jquery.foo = function () {
Alert (' This is a test. This is a test. ');
};
Of course, you can also add multiple global functions:

Copy Code code as follows:

Jquery.foo = function () {
Alert (' This is a test. This is a test. ');
};
Jquery.bar = function (param) {
Alert (' This function takes a parameter, which is "' + param + '". ');
};

The call is the same as a function: Jquery.foo (); Jquery.bar (); or $.foo (); $.bar (' Bar ');
(3) Selector plugin
1.2 To write jquery plug-ins need to be aware of:
(1) The recommended naming method for Plug-ins is: jquery. [Plugin name].js
(2) All object methods should be attached to the Jquery.fn object, and all global functions should be attached to the jquery object itself.
(3) Inside the plug-in, this refers to the jquery object currently being fetched by the selector, unlike the general method, where the internal this points to a DOM element.
(4) can traverse all the elements through This.each
(5) All methods or function plug-ins should end with semicolons, otherwise there may be problems with compression. To make it more safe to write, you can add a semicolon (;) to the header of the plugin, lest their nonstandard code affect the plug-in.
(6) The plugin should return a jquery object to ensure that the plug-in can be chained to operation.
(7) Avoid using the $ as the alias for the JQuery object within the plug-in, rather than using a full jquery representation. This prevents conflicts.
The mechanism of 1.3JQuery Plug-ins
jquery provides 2 ways to extend the jquery functionality. That
①jquery.fn.extend ()
②jquery.extend ()
The first one is what we said first in the plug-in type, and the second one is the 2 things that follow.
Jquery.extend () A very important function of the friend in the plug-in is to extend an object that already exists.
Like what:
var newsrc=$.extend (Dest,src1,src2,src3 ...)
It means to src1,src2,src3 ... Merged into Dest, the return value is the merged dest, which shows that the method is merged.
Example:
var result=$.extend ({},{name: "Tom", Age:21},{name: "Jerry", Sex: "Boy"})
The results obtained are:
Result={name: "Jerry", Age:21,sex: "Boy"}
Detailed can be viewed: Jquery.extend function DetailedThere is a good explanation for this method.

Official website: jquery.extend () and JQuery.fn.extend ()
using namespaces
Although in the jquery namespace, we prohibit the use of a large number of JavaScript function names and variable names. But it is still inevitable that some functions or variables will be in conflict with other jquery plug-ins, so we are accustomed to encapsulating some methods into another custom namespace.
Copy Code code as follows:

Jquery.myplugin = {
Foo:function () {
Alert (' This is a test. This is a test. ');
},
Bar:function (param) {
Alert (' This function takes a parameter, which is "' + param + '". ');
}
};

A function that takes a namespace is still a global function, and the method used when invoked:
Copy Code code as follows:

$.myplugin.foo ();
$.myplugin.bar (' Baz ');


two. First jquery plugin
If you need to write a jquery plugin, you need to add a property name to the $.fn object, which is actually your plugin name. Its general framework is as follows:
Copy Code code as follows:

(function ($) {
$.fn.myplugin = function () {
Here to start writing functional requirements
};
}) (JQuery);

Now we need to write the function of the plug-in is very simple, is to put an object to slowly hide. is to use the fadeout () method.
OK, we turn on VS 2012. Create a new JScript file and name it: Myplugin.js and add the following code inside:
Copy Code code as follows:

(function ($) {
$.fn.myplugin = function () {
This.fadeout (' normal ');
};
}) (JQuery);

How to use it? Very simple.
Create a new HTML page and import the jquery file as well as our Myplugin.js file into this page. As follows:
Copy Code code as follows:

<script src= "Scripts/jquery-1.4.1.js" type= "Text/javascript" ></script>
<script src= "Myplugin.js" type= "Text/javascript" ></script>
JS Code:
<script type= "Text/javascript" >
$ (document). Ready (function () {
$ ("#btn1"). Click (function () {
$ ("#div1"). Myplugin ();
});
});
</script>

HTML code:
Copy Code code as follows:

<div id= "Div1" style= "width:400px; height:30px; Background-color:gray; " >
My god</div>
<input id= "btn1" type= "button" value= "button" onclick= "Myclick" () "/>"

OK, when you click the button on the page now, the div will slowly hide ... Because we set the normal, it can also set some values and so on.
Very excited, since this has a smart tip, the following figure:

It!
three. Plug-ins are used in multiple element controls.
3.1 used in multiple element controls
4th of the places where you write jquery plug-ins, write that you can use the This.each method if you want to iterate. $ ("ID"). Each can traverse jquery objects, arrays, and collections.
Ok. Knowing this, our new code is as follows:

Copy Code code as follows:

(function ($) {
$.fn.hoverelement = function () {
This.each (function () {
$ (this). Hover (
function () {
$ (this). addclass ("Add");
},
function () {
$ (this). Removeclass ("Remove");
}
);
})
}
}) (JQuery);

The above main uses the. each () method to traverse. The code is very simple, is the current object's background color CSS style in "Add" and "Remove" directly switch.

The code for HTML is:
Copy Code code as follows:

<div class= "Hovertext" >
The "a" Button.
</div>
<div class= "Hovertext" >
Second Button.
</div>
<div class= "Hovertext" >
Third Button.
</div>

JS Code:
Copy Code code as follows:

<script type= "Text/javascript" >
$ (document). Ready (function () {
$ (". Hovertext"). Hoverelement ();
});
</script>

Very simple, no explanation.
3.2-Chain operation
Chained operation? Have you ever heard of it ... For example, the following sentence:
$ ("#div1"). CSS ("Color", "red"). AddClass ("Add"). Animate ({"width": "100px"},1000);
is the ability to do more with the current element, through ".". This action is particularly chic.
So how do we achieve this effect? It's simple, I can just go back to the object. Note the 6th above: The plugin should return a jquery object to ensure that the plug-in can be chained to operation.
We still look at the example just now:
Copy Code code as follows:

(function ($) {
$.fn.hoverelement = function () {
Return This.each (function () {
$ (this). Hover (
function () {
$ (this). addclass ("Add");
},
function () {
$ (this). Removeclass ("Remove");
}
);
})
}
}) (JQuery);

The code is the same, the only difference is: This.each (function () {This front adds a return. This realizes our chain operation.
And then you're like:
Copy Code code as follows:

$ (document). Ready (function () {
$ (". Hovertext"). Hoverelement (). CSS ("Color", "yellow");
});

Can see the text has become a yellow color.

four Customize your own plug-ins
The style of a custom plug-in is essential for a business plug-in. We can change the default style of the developer by typing a different style on our own. For example, the most common width, height, url, color, and so on. Without these customizations, the value of the plugin developed by developers would have been greatly reduced.
OK, the following example means that when we hover an object, it can change its text, background, foreground three attributes, that is, texts, background colors, foreground colors. The user can set the value he wants to set instead of fixing to die. Of course, if the user does not set, we will give him a default value.
The development framework for defining such plug-ins is:
$.fn. Youplugin = function (options) {...}
In order to prevent some lazy people, we need to set some default values, when it is not set, we use these defaults.
var defaultval = {
Text: ' Your mouse is over ',
ForeColor: ' Red ',
BackColor: ' Gray '
};
How does the default value and user-transmitted values come together? This will require the $.extend () knowledge we talked about at the beginning.
var obj = $.extend (defaultval, Options);
This way, the user-defined values are overwritten with the default user's value. If the user does not define a value, it is customized using the system.
The code is as follows:
Copy Code code as follows:
(function ($) {
$.fn.texthover = function (options) {//options often use this to indicate a Xu Multiple parameters.
var defaultval = {
Text: ' Your mouse is over ',
ForeColor: ' Red ',
BackColor: ' Gray '
};
//default value
var obj = $.extend (defaultval, Options);
Return This.each (function () {
var selobject = $ (this);//Get current object
var OldText = Selobject.text ();//Get the current object's Te XT value
var oldbgcolor = selobject.css ("Background-color");//Get the background color of the current object
var oldcolor = selobject.css ("color"); The color of the current object's font
Selobject.hover (function () {//define a hover method.
Selobject.text (obj. Text);//Assignment
Selobject.css ("Background-color", obj. BackColor);//Assignment
Selobject.css ("Color", obj. ForeColor);//Assignment
},
function () {
Selobject.text (oldtext);
Selobject.css ("Background-color", Oldbgcolor);
Selobject.css ("Color", oldcolor);
}
);
});
}
}) (JQuery);

The code is also very simple, above all have some explanation, at the moment not wordy.
How to use it? Very simple.
HTML Code:
Copy Code code as follows:

<div id= "Div1" class= "Textbar" >
Mouse over here .....
</div>
<div id= "Div2" class= "Textbar" >
Mouse over here .....
</div>

JS Code:
Copy Code code as follows:

$ (document). Ready (function () {
$ (' #div1 '). Texthover ({
Text: ' I am going to over ... ',
ForeColor: ' Yellow ',
BackColor: ' Red '
});
$ (' #div2 '). Texthover ({Text: ' I am Second div ... '});
});

You can see the effect.
I hope it will be of help to you.
OK, so far, it should be a basic element of plug-in development. Originally there is a more complex code, together hair, and so on the next section!
SOURCE download

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.