Home > Web Front-end > JS Tutorial > A concise tutorial on writing Jquery plug-ins_jquery

A concise tutorial on writing Jquery plug-ins_jquery

WBOY
Release: 2016-05-16 16:54:40
Original
1118 people have browsed it

Copy code The code is as follows:
/*
1. The jQuery plug-in file name is recommended to be named jquery .[plugin name].js to avoid confusion with other JavaScript library plug-ins. For example, name it jquery.color.js
2. All object method names 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 general methods, such as the chick() method. The internal this points to the dom element
4. You can use this .each to traverse all elements
5. All methods or function plug-ins should end with a semicolon, otherwise problems may occur during compression. To be more secure, you can even add a semicolon at the head of the plug-in. No.,
to prevent other people’s non-standard codes from affecting the query.
6. The plug-in should return a jquery object to ensure that the plug-in can be chained. Unless the plug-in needs to return some amount that needs to be returned, such as a string or an array
7. Avoid using $ as an alias for the jquery object inside the plug-in, but use complete jquery to represent it, so as to avoid conflicts. Of course, you can also use the technique of closure to avoid the problem of
, so that the plug-in can continue to use $ as an alias for jquery.
*/

//;For better compatibility, there is a semicolon at the beginning
;(function($){//Here $ is used as the formal parameter of the anonymous function
//$.fn.extend extension plug-in
$.fn.extend({
"color":function(value){//color self-written plug-in method name
//jQuery provides css The method can be written directly as this.css("property","value");
return this.css("color",value);
}
});

}) (jQuery);//Here jquery is passed as an actual parameter to the anonymous function


function red(){
alert($("#div").color() "Prove that the plug-in is available ");
alert($("#div").color("red") "Proof that the plug-in returned a Jquery object");
$("#div").color("red") ;
}

Example of using plug-in in HTML:

Copy code The code is as follows:

dddddddddddddddd

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template