Home > Web Front-end > JS Tutorial > body text

A brief development guide for jQuery library plugins for JavaScript_jquery

WBOY
Release: 2016-05-16 15:45:32
Original
1119 people have browsed it

jQuery plug-ins are usually divided into two categories.

  1. Selector-based plug-in (supports chain operations)
  2. Plug-in not based on selector (does not support chain operation)

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);

Copy after login

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);

Copy after login

The calling form of this type of plug-in is generally $(selector).PluginName();.

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