$.extend () This is a convenient way to define some auxiliary methods.
1 $.extend ({2 sayhello:function (name) {3 console.log (' Hello:'+name '); 4 }5 }); 6 7 $.sayhello (" Zhang San "); // called
Second, $.fn
1 $.fn.myplugin=function () {2 //In this case, this refers to the element selected with jquery3 //For example: $ (' a '), then this=$ (' a ')4 this.css (' Color ', ' red ');5 This.each (function () {6 $ (this). Append (': ' +$ (This). attr (' href '));7 });8 }9 Ten //Support chaining calls One $.fn.myplugin = function () { A //In this case, this refers to the element selected with jquery - this.css (' Color ', ' red '); - return This.each (function () { the //operate on each element - $ (this). Append (' "+ $ (This). attr (' href ')); - }) - } + - + //Pass -through parameters A $.fn.myplugin = function (options) { at var defaults = { - ' color ': ' Red ', - ' fontSize ': ' 12px ' - }; - var settings = $.extend (defaults, options); - return This.css ({ in ' color ': Settings.color, - ' fontSize ': Settings.fontsize to }); + } * //methods to protect default parameters $ $.fn.myplugin = function (options) {Panax Notoginseng var defaults = { - ' color ': ' Red ', the ' fontSize ': ' 12px ' + }; A var settings = $.extend ({},defaults, options);//Use an empty object as the first argument the return This.css ({ + ' color ': Settings.color, - ' fontSize ': Settings.fontsize $ }); $ } - //Object-oriented + wrap your code with self-invoking anonymous functions the //define the Beautifier constructor - (function () {Wuyi var beautifier = function (Ele, opt) { the This . $element = Ele, - this.defaults = { Wu ' color ': ' Red ', - ' fontSize ': ' 12px ', About ' textdecoration ': ' None ' $ }, - this.options = $.extend ({}, this.defaults, opt) - } - //How to define Beautifier A Beautifier.prototype = { + beautify:function () { the return this. $element. css ({ - ' color ': This.options.color, $ ' fontSize ': this.options.fontSize, the ' textdecoration ': this.options.textDecoration the }); the } the } - //Using the Beautifier object in the plug- in in $.fn.myplugin = function (options) { the //Create a beautifier entity the var beautifier = new Beautifier (this, options); About //Call its method the return beautifier.beautify (); the } the})();
jquery Plugin Development