While browsing the codeproject website, I suddenly saw an article: How to write plugin in Jquery.
If you are good at E-writing, you can read the link above.
Now I combine the above website and my own thoughts to write this article. I hope to get support and understanding from the big guys. . . Big birds fly by. . . Welcome to take pictures.
Source:
【1】How to write plugin in Jquery.
【2】Sharp JQuery book
【3】Detailed explanation of JQuery.extend() of RascallySnake
1. Introduction
The purpose of writing the plug-in is to add value to existing A series of methods or functions are encapsulated so that they can be reused in other places and facilitate later maintenance.
In addition to providing a simple and effective way to manage elements and scripts, JQuery also provides an exceptional mechanism: adding its own methods and additional functions to the core module. Through this mechanism, Jquery allows us to create our own plug-ins and improve our efficiency in the development process.
1.1JQuery plug-ins are divided into 3 types:
(1) Plug-ins that encapsulate object methods (that is, object-level development)
This type of plug-in is the plug-in we need to talk about today .
(2) Plug-in that encapsulates global functions (class-level development)
means that independent functions can be added to the JQuery namespace.
To add a global function, we just need to define it as follows:
jQuery.foo = function() {
alert('This is a test. This is only a test.');
};
Of course 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 '".');
};
When called, it is the same as a function: jQuery.foo();jQuery. bar(); or $.foo();$.bar('bar');
(3) Selector plug-in
1.2 Things to note when writing JQuery plug-ins:
(1) Plug-in recommendations The naming method 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 points to the JQuery object currently obtained through the selector, unlike the general method, where the internal this points to the DOM element.
(4) You can traverse all elements through this.each
(5) All methods or function plug-ins should end with a semicolon, otherwise problems may occur during compression. In order to write more safely, you can add a semicolon (;) in the header of the plug-in to prevent their non-standard code from affecting the plug-in.
(6) The plug-in should return a JQuery object to ensure chainable operations of the plug-in.
(7) Avoid using $ as an alias for JQuery object inside the plug-in, but use complete JQuery to represent it. This avoids conflicts.
1.3 Mechanism of JQuery plug-in
JQuery provides 2 methods for extending JQuery functions. That is:
①jQuery.fn.extend()
②jQuery.extend()
The first one is the first case of the plug-in type we mentioned earlier, and the second one refers to the following two cases.
A very important function of jQuery.extend() in the plug-in is to extend the object of an existing object.
For example:
var newSrc=$.extend(dest,src1,src2,src3...)
It means to merge src1, src2, src3... into dest, and the return value is The merged dest, from which we can see that the method is merged.
Example:
var result=$.extend({},{name:"Tom",age:21},{name:"Jerry",sex:"Boy"})
The result obtained It is:
result={name:"Jerry",age:21,sex:"Boy"}
For details, you can view:
jQuery.extend function detailed explanation inside There is a good explanation of this method.
Official website:
JQuery.extend() and JQuery.fn.extend()Using namespaces
Although in the jQuery namespace, we It is forbidden to use a large number of javaScript function names and variable names. But it is still inevitable that some function or variable names 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 '".');
}
};
using namespace The function is still a global function, and the method used when calling:
$.myPlugin.foo();
$.myPlugin.bar('baz');
2. The first Jquery plug-in If you need 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() {
// Start writing the functional requirements here
};
})( jQuery );
Now we need to write The function of the plug-in is very simple, which is to slowly hide an object. Just use the fadeOut() method.
OK, let’s open VS 2012. Create a new jscript file and name it: MyPlugin.js, and add the following code in it:
(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 our MyPlugin.js file just now into this page. As follows:
js code:
HTML code:
Okay, now when you click the button on the web page, the div will slowly hide. . . Because what we set is normal, we can also set some values in it.
I’m very excited that this one has smart prompts, as shown below:
Let’s go!
3. Plug-ins are used in multiple element controls.
3.1 Use in multiple element controls
In the fourth point that needs to be paid attention to when writing a JQuery plug-in above, it is written that if you want to traverse, you can use this.each method. $("ID").each can traverse jquery objects, arrays and collections.
OK. Knowing 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 to traverse. The code is very simple, it just switches the background color css style of the current object directly between "Add" and "Remove".
HTML code is:
< ;div class="hoverText">
First Button..
Second Button..
div>
Third Button..
JS code:
Very simple, no explanation.
3.2 Chain operation
Chain operation? You’ve heard it all. . . For example, the following sentence:
$("#div1").css("color", "red").addClass("Add").animate({"width":"100px"},1000);
You can use "." after the current element to perform more operations. This action is particularly chic.
So how can we achieve this effect? It's very simple, I can just put the object back. Please note the sixth point above: the plug-in should return a JQuery object to ensure chainable operations of the plug-in.
Let’s still look at the example just now:
(function ($) {
$.fn.hoverElement = function () {
return this.each(function () {
$(this).hover(
function () {
$ (this).addClass("Add");
},
function () {
$(this).removeClass("Remove");
}
);
})
}
})(jQuery);
The codes are the same, the only difference is: this.each(function () { A return is added in front of this. This way Implemented our chain operation:
$(document).ready(function () {
$(".hoverText").hoverElement().css("color","yellow");
});
You can see that the text has turned into yellow color.
4 Customize your own plug-in
For a commercial plug-in, the custom plug-in is. Style is essential. We can change the developer's default style by inputting different styles, such as the most common width, height, url, color, etc. If there are no such custom things, then development will be difficult. OK, the following example means that when we hover an object, it can change its three attributes: text, background, and foreground. Text, background color, and foreground color. Users can set the values they want, rather than being fixed. Of course, if the user does not set them, we will give him a default value
to define the development of this type of plug-in. The framework 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 value.
var defaultVal = {
Text: 'Your mouse is over',
ForeColor: 'red',
BackColor: 'gray'
};
The default value and How are the values passed in by the user combined? This requires the $.extend() knowledge we talked about at the beginning.
var obj = $.extend(defaultVal, options);
In this case, the user-defined value overwrites the default user value. If the user does not define a value, the system-defined value is used.
The code is as follows:
(function ($) {
$.fn.textHover = function (options) {//options are 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);//Get the current object
var oldText = selObject.text();//Get the text value of the current object
var oldBgColor = selObject.css("background- color");//Get the background color of the current object
var oldColor = selObject.css("color");//Get the font color of the current object
selObject.hover(function () {//Definition A hover method.
selObject.text(obj.Text);//Assignment
selObject.css("background-color", obj.BackColor);//Assignment
selObject.css(" color", obj.ForeColor);//Assign value
},
function () {
selObject.text(oldText);
selObject.css("background-color", oldBgColor);
selObject.css("color", oldColor);
}
);
});
}
})(jQuery);
The code is also very simple. There are some explanations above, so I won’t be wordy at the moment.
How to use it? Very simple.
HTML code:
Mouse over here.....
Mouse over here.....
JS Code:
$(document).ready(function () {
$('#div1').textHover({
Text: 'I am going to over..',
ForeColor: 'yellow',
BackColor: 'Red'
});
$('#div2').textHover({ Text: 'I am second div. ..' });
});
to see the effect.
Hope this helps.
OK, so far, these should be the basic elements of a plug-in development. Originally there was a more complicated code later, which I posted together, so wait for the next section!
Source code download