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

不言
Release: 2023-04-03 10:28:02
Original
1498 people have browsed it

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!

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!