Home Backend Development PHP Tutorial What are the jQuery plug-ins? Sharing how to write jQuery plug-in

What are the jQuery plug-ins? Sharing how to write jQuery plug-in

Jul 21, 2018 pm 02:00 PM
jquery plugin

What is the jQuery plug-in? Common jQuery plug-ins are mainly divided into three types: plug-ins that encapsulate object methods; plug-ins that encapsulate global functions; and selector plug-ins. So what is the writing and use of each jQuery plug-in based on these three jQuery plug-ins? Next, let’s talk about the use and writing of jQuery plug-ins.

jQuery plug-in classification:

1. Plug-in that encapsulates object methods

This kind of plug-in encapsulates object methods and is used to It is the most common plug-in to operate on jQuery objects obtained through selectors.

2. Plug-in that encapsulates global functions

You can add independent functions to the jQuery namespace. For example, the jQuery.noConflict() method, the commonly used jQuery.ajax() method, and the jQuery.trim() method that removes the first space are all plugins attached to the kernel as global functions within jQuery.

3. Selector plug-in

In some cases, you will need to use a selector plug-in.

Basic points of plug-ins

1. It is recommended that the file name of the jQuery plug-in be named jquery.[plug-in name].js to avoid confusion with other JavaScript library plug-ins.

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 general methods, such as the click() 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. To be more secure, you can even add a semicolon to the header of the plug-in to prevent other people's irregular code from affecting the plug-in.

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 quantity that needs to be obtained, such as a string or array, etc.

7. Avoid using $ as an alias for jQuery objects inside the plug-in. Instead, use complete jQuery to represent it. This can avoid conflicts. Of course, you can also use closure techniques to avoid this problem, so that the plug-in can continue to use $ as an alias for jQuery. Many plugins do this.

Closures in plug-ins

Regarding closures, ECMAScript briefly describes them: allowing the use of internal functions (that is, function definitions and function expressions located in another within the body of a function), furthermore, these inner functions have access to all local variables, parameters and other inner functions declared in the outer function in which they are contained, when one of such inner functions is called outside the outer function containing them , a closure will be formed. That is, the inner function will be executed after the outer function returns. When this internal function is executed, it still must access the local variables, parameters and other internal functions of its external function. The values ​​of these local variables, parameters, and function declarations (initially) are the values ​​when the outer function returns, but will also be affected by the inner function.

First define an anonymous function function(){/*Place code here*/}, and then enclose it in parentheses to become (function(){/*Place code here*/}). Finally, it is executed through the () operator. Parameters can be passed in for use by internal functions.

//Note that for better compatibility, there is a semicolon before the start:

;(function($){ //开始时将$作为匿名函数的形参
 
/*这里放置代码,可以使用$作为jQuery的缩写别名*/
 
})(jQuery); //这里就将jQuery作为实参传递给匿名函数了
Copy after login

The above is the structure of a common jQuery plug-in.

The mechanism of jQuery plug-in

jQuery provides two methods for extending jQuery functions, namely jQuery.fn.extend() method and jQuery.extend() method. The former is used for the first of the three plug-in types mentioned before, and the latter is used to extend the latter two plug-ins. Both methods accept one parameter, of type Object. The "name/value pairs" of the Object object respectively represent "function or method name/function body".

In addition to being able to extend jQuery objects, the jQuery.extend() method also has a powerful function, which is to use and extend existing Object objects.

The jQuery code is as follows:

jQuery.extend(target,obj1,…….[objN])
 
   用一个或多个其它对象来扩展一个对象,然后返回被扩展的对象。
   例如合并settings对象和options对象,修改并返回settings对象。
 
 
var settings={validate:false,limit:5,name:”foo”};
 
var options={validate:true,name:”bar”};
 
var newOptions=jQuery.extend(settings,options);
Copy after login

The result is:

newOptins={valitdate:true,limit:5,name:”bar”};
Copy after login

The jQuery.extend() method is often used to set a series of default parameters of the plug-in method, such as the following code Shown:

function foo(options){
 
options=jQuery.extend({
 
name:”bar”,
 
limit:5,
 
datatype:”xml”
 
},options);
 
};
Copy after login

If the corresponding value is set in the passed parameter options object when calling the foo() method, then the set value will be used, otherwise the default value will be used. The code is as follows:

foo({name:”a”,length:”4”,dataType:”json”});
 
foo({name:”a”,length:”4”});
 
foo({name:”a”});
 
foo();
Copy after login

By using the jQuery.extend() method, you can easily override the default value with the passed in parameters. At this point, the method call remains the same, except that a map is passed in instead of a parameter list. This mechanism is not only more flexible but also more concise than the traditional method of detecting each parameter. In addition, using named parameters means that adding new options will not affect the code written in the past, making it more intuitive and clear for developers to use.

Writing a jQuery plug-in

1. A plug-in that encapsulates the jQuery object method

Writing a plug-in that sets and gets the color

First introduce how Write a color() plug-in. This plug-in is used to implement the following two functions.

(1)设置匹配元素的颜色。

(2)获取匹配的元素(元素集合中的第1个)的颜色。

首先将该插件按规范命名为jquery.color.js。

然后再JavaScript文件里搭好框架.由于是对jQuery对象的方法扩展,因此采用第1类方法jQuery.fn.extend()来编写。

 ;(function($){
 
$.fn.extend({
 
“color”:function(value){
 
//这里写插件代码
 
}
 
});
 
})(jQuery);
Copy after login

这里给这个方法提供一个参数value,如果调用了方法的时候传递了value这个参数,那么就是用这个值来设置字体颜色;否则就是匹配元素的字体颜色的值。

首先,实现第1个功能,设置字体颜色。注意,由于插件内部的this指向的是jQuery对象,而非普通的DOM对象。代码如下:

;(function($){
 
$.fn.extend({
 
“color”:function(value){
 
return this.css(“color”,value);
 
}
 
});
 
})(jQuery);
Copy after login

接下来实现第2个功能。如果没用给方法传递参数,那么就是获取集合对象中第1个对象的color的值。由于css()方法本身就具有返回第1个匹配元素样式值的功能,因此此处无需通过eq()来获取第1个元素。只要这两个方法结合起来,判断一下value的值是否是undefined即可。

jQuery代码如下:

;(function($){
 
$.fn.extend({
 
“color”:function(value){
 
if(color===undefined){
 
return this.css(“color”,value);
 
}else{
 
Return this.css(“color”,value);
 
}
 
}
 
});
 
})(jQuery);
Copy after login

这样一来,插件也就完成了。现在来测试一下代码。

<script type=”text/javascript”>
 
//插件编写
 
;(function($){
 
$.fn.extend({
 
“color”:function(value){
 
if(color===undefined){
 
return this.css(“color”,value);
 
}else{
 
Return this.css(“color”,value);
 
}
 
}
 
});
 
})(jQuery);
 
 
 
//插件应用
 
$(function(){
 
//查看第一个div的color样式值
 
alert($(“div”).color()+”\n返回字符串,证明此插件可用。”);
 
//把所有的div字体颜色都设为红色
 
alert($(“div”).color(“red”)+”\n返回object证明得到的是jQuery对象。“);
 
})
 
</script>
 
<div style=”color:red”>red</div>
 
<div style=”color:blue”>blue</div>
 
<div style=”color:green”>green</div>
 
<div style=”color:yellow”>yellow</div>
    另外,如果要定义一组插件,可以使用如下所示的写法:
 
:(function($){
 
$.fn.extend({
 
"color":function(value){
 
//插件代码
 
},
 
"border":function(value){
 
//插件代码
 
},
 
"background":function(value){
 
//插件代码
 
}
 
};
 
})(jQuery);
Copy after login

表格隔行变色插件

表格隔行变色的代码如下:

$("tbody>tr:odd").addClass("odd");
 
$("tbody>tr:even").addClass("even");
 
$(&#39;tbody>tr&#39;).click(function(){
 
//判断是否选中
 
var hasSelected=$(this).hasClass(&#39;selected&#39;);
 
//如果选中,则移出selected类,否则就加上selected类
 
$(this)[hasSelected?"removeClass":"addClass"](&#39;selected&#39;)
 
//查找内部的checkbox,设置对应的属性
 
.find(&#39;checkbox&#39;).attr(&#39;checked&#39;.!hasSelected);
 
});
 
 
 
//如果复选框默认情况下是选择的,则高色
 
$(&#39;tbody>tr:has(:checked)&#39;).addClass(&#39;selected&#39;);
Copy after login

首先把插件方法取名为alterBgColor,然后为该插件方法搭好框架,jQuery代码如下:

;(function($){
 
$.fn.extend({
 
"alterBgColor":function(options){
 
//插件代码
 
}
 
});
 
})(jQuery);
Copy after login

框架完成后,接下来就需要为options定义默认值。默认构建这样({odd:"odd",even:"even",selected:"selected"})一个Object。这样就可以通过$("#sometable").alterBgColor({odd:"odd",even:"even",selected:"selected"})自定义奇偶行的样式类名以及选中后的样式类名。同时,直接使用$("#sometable").alterBgColor()就可以应用 默认的样式类名。

jQuery代码如下:

;(function($){
 
$.fn.extend({
 
"alterBgColor":function(options){
 
options=$.extend({
 
odd:"odd", /*偶数行样式*/
 
even:"even", /*奇数行样式*/
 
selected:"selected" /*选中行样式*/
 
},options);
 
}
 
});
 
})(jQuery);
Copy after login

如果在后面的程序中需要使用options对象的属性,可以使用如下的方式来获得:

options.odd; //获取options对象中odd属性的值
 
options.even; //获取options对象中even属性的值
 
options.selected; //获取options对象中selected属性的值
Copy after login

接下来就需要把这些值放到程序中,来代替先前程序中的固定值。

最后就是匹配元素的问题了。显然不能直接用$('tbody>tr')选择表格行,这样会使页面中全部的元素都隔行变色。应该使用选择器选中某个表格,执行alterBgColor()方法后,将对应的表格内元素进行隔行变色。因此,需要把所有通过$('tbody>tr')选择的对象改写成$('tbody>tr',this),表示在匹配的元素内(当前表格内)查找,并应用上一步中的默认值。jQuery代码如下:

;(function($){
 
$.fn.extend({
 
"alterBgColor":function(options){
 
//设置默认值
 
options=$.extend({
 
odd."odd",
 
even."even",
 
selected:"selected"
 
},options);
 
$("tbody>tr:odd",this).addClass(options,odd);
 
$("tbody>tr:even",this).addClass(options,even);
 
$("tbody>tr",this).click(function(){
 
//判断是否选中
 
var hasSelected=$(this).hasClass(options,selected);
 
//如果选中,则移出selected类,否则加上selected类
 
$(this)[hasSelected?"removeClass":"addClass"](options,selected)
 
//查找内部的checkbox,设置对应属性
 
.find(&#39;:checkbox&#39;).attr(&#39;checked&#39;,!hasSelected);
 
});
 
//如果单选框默认情况下是选择的,则高色
 
$(&#39;tbody>tr:has(:checkd),this&#39;).addClass(options,selected);
 
rerturn this; //返回this,使方法可链
 
}
 
});
 
})(jQuery);
Copy after login

在代码的最后,返回this,让这个插件具有可链性。
此时,插件就完成了。现在来测试这个插件。构造两个表格,id分别为table1和table2,然后使用其中一个

调用alterBgColor()方法,以便查看是否能独立工作,并且具有可链性。
jQuery代码如下:

$(&#39;#table2&#39;)
.alterBgColor() //应用插件
 
.find("th").css("color","red"); //可链式操作
Copy after login

需要注意的是,jQuery的选择符可能会匹配1个或者多个元素。因此,在编写插件时必须考虑到这些情况。可以在插件内部调用each()方法来遍历匹配元素,然后执行相应的方法,this会依次引用每个DOM元素。如下jQuery代码所示:

 ;(function($)){
 
$.fn.extend({
 
"SomePlugin":function(options){
 
return this.each(function(){
 
//这里置放代码
 
});
 
}
 
});
 
})(jQuery);
Copy after login

相关推荐:

jQuery简单滚动插件

jquery.tmpl JQuery模板插件_jquery

The above is the detailed content of What are the jQuery plug-ins? Sharing how to write jQuery plug-in. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

Explain the difference between self::, parent::, and static:: in PHP OOP. Explain the difference between self::, parent::, and static:: in PHP OOP. Apr 09, 2025 am 12:04 AM

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

How does PHP handle file uploads securely? How does PHP handle file uploads securely? Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles