Learn about jquery with me plugin development tutorial

Source: Internet
Author: User

Excerpt from: http://www.poluoluo.com/jzxy/201204/163035.html

While visiting CodeProject website, I suddenly saw an article: How to write plugin in Jquery.  
If the E-text good classmate, you can see the above connection.
Now I write this article on the above website and the combination of my own ideas. Hope to get the support and understanding of Daniel ... The Big Bird flies over ... Welcome to the dress.
Source:

"1" How to write plugin in Jquery.

"2" a sharp jquery book

"3" Rascallysnake's Jquery.extend () detailed
I. Introduction
The purpose of the plug-in is to provide an encapsulation of a series of methods or functions that are already in place, 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 to the mechanism of adding its own methods and additional functionality to the core modules. With this mechanism, jquery allows us to create our own plugins to improve our efficiency in the development process.

The 1.1JQuery plug-in is divided into 3 types:
(1) Plug-in for encapsulating object methods (i.e., object-level development)
This type of plugin is the plugin we need to talk about today.
(2) Plug-in for encapsulating global functions (class-level development)
Refers to the ability to add separate functions under the jquery namespace.
To add a global function, we just need to define the following:
Jquery.foo = function () {
Alert (' This is a test. This was only a test. ');
};
Of course you can also add multiple global functions:

.The code is as follows:
Jquery.foo = function () {
Alert (' This is a test. This was only a test. ');
};
Jquery.bar = function (param) {
Alert (' This function takes a parameter, which is "' + param + '".);
};


called when it is the same as a function: Jquery.foo (); Jquery.bar (); or $.foo (); $.bar (' Bar ');
(3) Selector plug-in
1.2 What to note about writing jquery plugins:
(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 appended to the JQuery object itself.
(3) inside the plug-in, this is the jquery object currently fetched through the selector, and unlike the normal method, the internal this point is the DOM element.
(4) All elements can be traversed by This.each
(5) All methods or function plug-ins should end with a semicolon, or the problem may occur when compressing. To be more insured, you can add a semicolon (;) to the plugin's head to prevent their irregular code from affecting the plugin.
(6) The plugin should return a jquery object in order to ensure the plug-in's chained operation.
(7) Avoid using $ as an alias for jquery objects inside a plug-in, instead use the full jquery to represent it. This avoids conflicts.
1.3JQuery plug -in mechanism
jquery provides 2 ways to extend the functionality of jquery. namely:
①jquery.fn.extend ()
②jquery.extend ()
The first one is what we said earlier in the first case of the plug-in type, the second one refers to the following 2 cases.
Jquery.extend () a very important function in the plugin is to extend an object that already has objects.
For example:
var newsrc=$.extend (dest,src1,src2,src3 ...)
its meaning is to be src1,src2,src3 ... Merge into Dest, and the return value is the merged dest, so you can see that the method is merged.
Example:
var result=$.extend ({},{name: "Tom", Age:21},{name: "Jerry", Sex: "Boy"})
The resulting results are:
result={name: "Jerry", Age:21,sex: "Boy"}
details can be viewed at:jquery.extend Function ExplanationThere 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. 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.

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


The function that takes the namespace is still the global function, the method that is used when calling:

.The code is 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 after the $.fn object, which is actually your plugin name. Its general framework is as follows:

.The code is as follows:
(function ($) {
$.fn.myplugin = function () {
Start writing functional Requirements here
};
}) (JQuery);


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

.The code is 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 and just our Myplugin.js file into this page. As follows:

.The code is 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:

.The code is 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 ()"/>


Well, now that you click on the button on the page, the div will slowly hide ... Because we set the normal, it can also set some values and the like.
The excitement is that since this has smart hints, such as:

It!
three. Plug-ins are used in multiple element controls.
3.1 Applied in multiple element controls
The 4th place to note in writing the jquery plugin above is that you can use the This.each method if you want to traverse. $ ("ID"). Each can traverse jquery objects, arrays, and collections.
Ok. Knowing this, our new code looks like this:

.The code is as follows:
(function ($) {
$.fn.hoverelement = function () {
This.each (function () {
$ (this). Hover (
function () {
$ (this). addclass ("Add");
},
function () {
$ (this). Removeclass ("Remove");
}
);
})
}
}) (JQuery);


The. each () method is used primarily for traversal. The code is simple, which is to switch the current object's background-color CSS style to "ADD" and "Remove" directly.

The code for the HTML is:

.The code is as follows:
<div class= "Hovertext" >
First Button:
</div>
<div class= "Hovertext" >
Second Button.
</div>
<div class= "Hovertext" >
Third Button.
</div>


JS Code:

.The code is as follows:
<script type= "Text/javascript" >
$ (document). Ready (function () {
$ (". Hovertext"). Hoverelement ();
});
</script>


Very simple, not explained.
3.2 Chain Operation
Chained operation? I've heard it all before. For example, the following sentence:
$ ("#div1"). CSS ("Color", "red"). AddClass ("Add"). Animate ({"width": "100px"},1000);
is to be able to implement more operations with "." Behind the current element. This movement is particularly chic.
So how do we achieve this effect? It's easy, I can just get the object back. Note the 6th above: The plugin should return a jquery object in order to guarantee the plug-in's chained operation.
We still look at just the example:

.The code is as follows:
(function ($) {
$.fn.hoverelement = function () {
Return This.each (function () {
$ (this). Hover (
function () {
$ (this). addclass ("Add");
},
function () {
$ (this). Removeclass ("Remove");
}
);
})
}
}) (JQuery);


Code is the same, the only difference is: This.each (function () {This is preceded by a return. This enables us to chain-operate.
And then you do:

.The code is as follows:
$ (document). Ready (function () {
$ (". Hovertext"). Hoverelement (). CSS ("Color", "yellow");
});


can see that the text has become yellow color.  

IV customizing its own plug-in  
Custom plugin styles are essential for a business plug-in. We can change the developer's default style by entering different styles for ourselves. For example, the most common width, height, url, color, and so on. Without these customizations, the developer-developed plug-in will have a significantly reduced value for use.  
OK, the following example means that when we hover an object, it can change its text, background, foreground three properties, that is, the literal, the background color, the foreground color. The user can set the value he wants to set, rather than fixing it to death. 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) {...}  
in order to prevent some lazy people, we need to set some default values, when it is 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 values that the user passes in? This will require the $.extend () knowledge we talked about at the outset.  
var obj = $.extend (defaultval, Options),  
This overrides the default user value for the user-defined value. If the user does not define a value, it is customized with the system.  
code is as follows:  

.The code is as follows:
(function ($) {
$.fn.texthover = function (options) {//options often use this 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);//Get current Object
var oldtext = Selobject.text ();//Gets the text value of the current object
var oldbgcolor = selobject.css ("Background-color");//Gets the background color of the current object
var oldcolor = selobject.css ("color");//Gets the color of the current object's font
Selobject.hover (function () {///defines a hover method.
Selobject.text (obj. Text);//Assign Value
Selobject.css ("Background-color", obj. BackColor);//Assign Value
SELOBJECT.CSS ("Color", obj.) ForeColor);//Assign Value
},
function () {
Selobject.text (OldText);
Selobject.css ("Background-color", Oldbgcolor);
SELOBJECT.CSS ("Color", oldcolor);
}
);
});
}
}) (JQuery);


The code is simple, there are some explanations on it, and it is not wordy at the moment.
How to use it? Very simple.
HTML Code:

.The code is as follows:
<div id= "Div1" class= "Textbar" >
Mouse over here .....
</div>
<div id= "Div2" class= "Textbar" >
Mouse over here .....
</div>


JS Code:

.The code is 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, sent together, wait for the next section!

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.