jQuery plug-ins are usually divided into two categories.
I briefly learned jQuery plug-in development some time ago and developed two simple plug-ins. Here is a brief summary of the development models of the two plug-ins.
Selector based plugin
The usual development model is as follows:
(function($, window, undefined) { $.fn.PluginName = function(opts) { var defaults = { // 插件自定义选项的默认值 }; // 以用户的自定义选项覆盖默认选项 var options = $.extend(defaults, opts || {}); return this.each(function() { // 让插件支持链式操作 // 在这里编写插件功能代码 }); }; })(jQuery, window);
First, create an anonymous self-executing function with formal parameters $ , window and undefined and actual parameters jQuery and window.
Huh? Why is there no corresponding actual parameter passed in for undefined? This is a little trick. Considering that the variable name undefined may have been assigned a value in JavaScript code elsewhere and lost its true meaning, so we simply do not pass in this parameter here to ensure that it is in the anonymous self-executing function. Really undefined.
After jQuery is passed in, it corresponds to $. This ensures that the $ called in the plug-in must be jQuery and not a library such as Prototype.
The calling method of this type of plug-in is generally in the form of $(selector).PluginName();.
Such specific examples can be found at https://github.com/libuchao/KTwitter
Non-selector based plugins
Since this type of plug-in does not rely on selectors, there is no chain operation. The general development model is as follows:
(function($, window, undefined) { $.PluginName = function(opts) { var defaults = { // 插件自定义选项的默认值 }; // 以用户的自定义选项覆盖默认选项 var options = $.extend(defaults, opts || {}); // 在这里编写插件功能代码 }; })(jQuery, window);
The calling form of this type of plug-in is generally $(selector).PluginName();.