1. Plug-in that encapsulates object methods
To write this type of plug-in, you need to use the jQuery.fn.extend() method provided by JQuery. The steps to implement the custom function for querying color are as follows
1.1 Name the written plug-in file jquery.color.js
1.2 Writing the content of the plug-in
;(function($){ jQuery.fn.extend({//这里也可以写成$.fn.extend "color":function(value){//value是颜色值 return this.css("color",value); }, "border":function(value){ //插入代码 } }); })(jQuery);
2. Plug-in that encapsulates global functions
This type of plug-in adds functions inside the jQuery namespace. To write such plug-ins, you need to use the jQuery.extend() method provided by JQuery. Write a function that removes the spaces on the left side of the string
;(function($){ $.extend({ ltrim:function(text){//需要去除空格的字符串 return (text || "").replace(/^\s+/g, ""); }, rtrim:function(text){ return (text || "").replace(/\s+$/g, ""); } }); })(jQuery);
Then you can use $.rtrim(" test ") or jQuery.ltrim(" test "); to return the string with the spaces removed. The function is similar to jQuery's trim() function.
3. Selector plug-in
To write the between selector plug-in description, for example, use
(“p:gt(1)”) explains with examples
The source code of the :gt() selector in jQuery is
gt:function(a,i,m){ return i > m[3]-0; }
, where
a points to the DOM element currently traversed.
i represents the index value of the currently traversed DOM element
m is a special array.
m[0] = :gt(1) The expression to be parsed
m[1] = :
m[2] = gt
m[3] = 1
Write this selector code with reference to
;(function($){ $.extend(jQuery.expr[":"], { between : function(a, i, m){ var tmp = m[3].split(",");//m[3]值为[2,5]; return tmp[0]-0 < i && i < tmp[1]-0; } }); })(jQuery);
The above is the detailed content of How to write jquery custom plug-in. For more information, please follow other related articles on the PHP Chinese website!