JQuery plugin Development)

Source: Internet
Author: User

JQuery plug-in Development (transfer) and jquery plug-in development

When I visited the codeproject website, I suddenly saw an article: How to write plugin Jquery.
If you are good at E, you can check the connection above.
Now I am writing this article based on the above website and my own ideas. Hope you can get the support and understanding from everyone... The big bird flew over... Welcome to shoot.
Source:

[1] How to write plugin in Jquery.

[2] A sharp JQuery book

[3] RascallySnake's JQuery. extend ()
I. Introduction 
The purpose of writing plug-ins is to encapsulate a series of existing methods or functions so that they can be used repeatedly in other places for later maintenance.
In addition to providing a simple and effective way to manage elements and scripts, JQuery also provides an exceptional mechanism: to add its own methods and additional functions to the core module.

With this mechanism, Jquery allows us to create our own plug-ins, improving our development efficiency.

1.1 JQuery plug-ins are classified into three types:
(1) plug-ins that encapsulate object methods (that is, object-level development)
This type of plug-ins is what we need to talk about today.
(2) plug-ins that encapsulate global functions (Class-level development)
An independent function can be added to the JQuery namespace.
To add a global function, we only need to define it as follows:
JQuery. foo = function (){
Alert ('this is a test. This is only a test .');
};
You can also add multiple global functions:

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

The call time is the same as that of a function: jQuery. foo (); jQuery. bar (); or $. foo (); $. bar ('bar ');
(3) selector plug-in


1.2 notes for writing the JQuery plug-in:
(1) recommended plug-in naming method: jquery. [plug-in name]. js
(2) All object methods should be appended to the JQuery. fn object, and all global functions should be appended to the JQuery object itself.
(3) inside the plug-in, this points to the JQuery object currently obtained through the selector. Unlike the general method, the internal this points to the DOM element.
(4) you can use this. each to traverse all elements.
(5) All method or function plug-ins,Should end with a semicolon; otherwise, problems may occur during compression. You can add a semicolon (;) to the plug-in Header for more secure writing (;)To avoid the impact of their nonstandard code on the plug-in.
(6) The plug-in should return a JQuery object to ensure the chained operation of the plug-in.
(7) Avoid using $ as the alias of the JQuery object in the plug-in, instead of using the complete JQuery representation. This avoids conflicts.

 
1.3JQuery plug-in mechanism
JQuery provides two methods for extending JQuery functions. That is:
① JQuery. fn. extend ()
② JQuery. extend ()
The first is the first case of the plug-in type,

The second case refers to the two following cases.
JQuery. extend () has a very important function in the plug-in. It is used to expand existing object objects.
For example:
Var newSrc = $. extend (dest, src1, src2, src3 ...)
It means to merge src1, src2, src3... into dest, and the returned value is the merged dest. From this we can see that this method is merged.
Example:
Var result = $. extend ({}, {name: "Tom", age: 21 },{ name: "Jerry", sex: "Boy "})
The result is:
Result = {name: "Jerry", age: 21, sex: "Boy "}
For details, refer to: This method is well explained in the jQuery. extend function details.

Official Website: JQuery. extend () and JQuery. fn. extend ()
Use namespace
Although a large number of javaScript function names and variable names are not allowed in the jQuery namespace. But it is still inevitable that some functions or variables will conflict with other jQuery plug-ins, so we are used to encapsulating some methods into another custom namespace.

jQuery.myPlugin = {   foo:function() {     alert('This is a test. This is only a test.');   },   bar:function(param) {     alert('This function takes a parameter, which is "' + param + '".');   } }; 

The namespace function is still a global function. The method used for calling is as follows:

$.myPlugin.foo(); $.myPlugin.bar('baz'); 

II. The first Jquery plug-in 
To write a JQuery plug-in, you need to add an attribute name after the $. fn object. This attribute name is actually your plug-in name. Its general framework is as follows:

(Function ($) {$. fn. myPlugin = function () {// write function requirements start here};}) (jQuery );

The plug-in function we need to write is simple, that is, to hide an object slowly. The method fadeOut () is used.
OK. Open VS 2012. Create a jscript file named MyPlugin. js and add the following code to it:

(function ($) {   $.fn.myPlugin = function () {     this.fadeOut('normal');   }; })(jQuery); 

How to use it? Very simple.
Create an html page and import the jquery file and MyPlugin. js file to this page. 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:

<div id="div1"> My God</div> <input id="btn1" type="button" value="button" onclick="MyClick()" /> 

Okay. When you click the button on the webpage, The div will be hidden slowly... Because we set normal, some values can also be set in it.
I am very excited that since there is a smart prompt, such:

 


3. Plug-ins are used in multiple element controls. 
3.1 used in multiple element controls
The fourth point of attention in writing the JQuery plug-in above, writes that if you want to traverse, you can use this. each method. $ ("ID"). each can traverse jquery objects, arrays, and collections.
OK. Now that we know this, our new code is as follows:

(function ($) { $.fn.hoverElement = function () {   this.each(function () {     $(this).hover(       function () { $(this).addClass("Add"); },       function () {$(this).removeClass("Remove"); }     );   }) } })(jQuery); 

The above mainly uses the. each () method for traversal. The code is very simple, that is, to directly switch the background color css style of the current object in "Add" and "Remove.

The HTML code is:

<div class="hoverText"> First Button.. </div> <div class="hoverText"> Second Button.. </div> <div class="hoverText"> Third Button.. </div> 

JS Code:

<script type="text/javascript"> $(document).ready(function () {   $(".hoverText").hoverElement(); }); </script> 

It is very simple, not explained.

 
3.2 chain operations
Chain Operation? Have you heard of it... For example:
$ ("# Div1" ).css ("color", "red"). addClass ("Add"). animate ({"width": "100px"}, 1000 );
That is, more operations can be performed through "." after the current element. This action is extremely chic.
So how can we achieve this effect? It's easy. I only need to get the object back. Note the sixth point above: the plug-in should return a JQuery object to ensure that the plug-in can be chained.
We still look at the example below:

(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 that this. each (function () {adds a return before this. In this way, our chained operations are implemented.
Then you:

$(document).ready(function () {   $(".hoverText").hoverElement().css("color","yellow"); }); 

The text has become yellow.

4. Customize your own plug-ins
For a commercial plug-in, the style of the custom plug-in is essential. We can change the developer's default style by entering different styles. For example, the most common width, height, url, color, and so on. Without such customization, the value of using plug-ins developed by developers will be greatly reduced.
OK. The following example indicates that when we hover an object, it can change its text, background, and foreground attributes, that is, text, background color, and foreground color. The user can set the value he wants, rather than the fixed value. Of course, if the user is not set, we will give him a default value.
The development framework for defining such plug-ins is:
$. Fn. YouPlugin = function (options ){...}
To prevent lazy people, we need to set some default values. When they are not set, we use these default values.
Var defaultVal = {
Text: 'Your mouse is over ',
ForeColor: 'red ',
BackColor: 'Gray'
};
How is the default value combined with the value passed in by the user? This requires the $. extend () knowledge we mentioned at the beginning.
Var obj = $. extend (defaultVal, options );
In this way, the user-defined value will overwrite the Default User value. If the user does not define the value, it is customized by the system.
The Code is as follows:

(Function ($) {$. fn. textHover = function (options) {// options this is often used to indicate that there are many 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); // obtain the current object var oldText = selObject. text (); // obtain the text value of the current object var oldBgColor = selObject.css ("background-color "); // obtain the background color of the current object var oldColor = selObject.css ("color"); // obtain the color of the current object font selObject. hover (
Function () {// defines a hover method. SelObject. text (obj. text); // assign selObject.css ("background-color", obj. backColor); // assign selObject.css ("color", obj. foreColor); // assign values}, function () {selObject. text (oldText); selObject.css ("background-color", oldBgColor); selObject.css ("color", oldColor) ;}) (jQuery );

The Code is also very simple. I have explained some of the above, but it is not a problem at the moment.
How to use it? Very simple.
HTML code:

<div id="div1" class="textBar"> Mouse over here..... </div> <div id="div2" class="textBar"> Mouse over here..... </div> 

JS Code:

$(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.
Hope to help you.
Okay, so far, it should be the basic elements of plug-in development.

There is a complicated code later, which is sent together. Wait for the next section!

Related Article

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.