search
HomeWeb Front-endJS TutorialShare study notes of jQuery plug-in_jquery

Plugin is also called jQuery Extension, which is a program written according to a certain standard application interface. There are currently more than thousands of jQuery plug-ins, which are written, verified and improved by developers from all over the world. For jQuery developers, using these plug-ins directly will quickly stabilize the system architecture and save project costs.

1. Plugin Overview

The plug-in is based on the core code of jQuery to write an application that combines certain specifications. In other words, the plug-in is also jQuery code, which can be inserted through the introduction of js files.

There are many types of plug-ins, which can be roughly divided into: UI class, form and verification class, input class, special effects class, Ajax class, sliding class, graphics and image class, navigation class, comprehensive tool class, animation class, etc.

Introducing plug-ins requires certain steps, which are basically as follows:

  • 1. The jquery.js file must be imported first, and before all plug-ins;
  • 2. Introduce plug-ins;
  • 3. Introduce plug-in peripherals, such as skins, Chinese language packs, etc.

For example, the most commonly used form validation plug-in: validate, in addition to the most basic plug-in file jquery.validate.min.js, there are also messages_zh.js and other language packages from various countries for you to use.

How to use this plug-in will not be described here. You can check out the video on MOOC.com about the jQuery plug-in - Validation Plugin, which describes in detail the various configuration items and extensions of this plug-in.

By analogy, for an excellent plug-in, detailed documentation is essential. Reading the documentation in detail and testing it locally will allow you to quickly get started using various plug-ins.

There are also various plug-ins written by others that you can use: such as plug-ins for managing cookies – cookies, etc.

Plug-ins can be found in the plug-in module on the jQuery official website. The jQuery Plugin Registry

2. Custom plug-in

Earlier we used good plug-ins provided by others, which are very convenient to use. If you can't find a plug-in that you are satisfied with on the market, and want to package a plug-in yourself for others to use. Then you need to write a jQuery plug-in yourself.

1. Types of plug-ins

According to functional classification, plug-in forms can be divided into the following three categories:

  • Plug-in that encapsulates object methods; (that is, a jQuery object based on a certain DOM element, localized, and most used)
  • Plug-in that encapsulates global functions; (global encapsulation)
  • Selector plugin. (Similar to .find(), for example: color(red) to select all red elements)

2. Basic points of plug-ins

Mainly used to solve various conflicts, errors and other problems caused by plug-ins, including the following:

  • It is recommended to use jQuery.[plugin name].js for the plug-in name to avoid conflicts with other js files or other libraries (you can use alert( $.[plug-in name]) to verify whether the global method exists );
  • The local object is attached to the jQuery.fn object, and the global function is attached to the jQuery object itself (you can use alert( $(selector).[plugin name]) to verify whether the local method exists);
  • Inside the plug-in, this points to the current local object (jQuery object obtained through the selector);
  • You can use this.each to traverse all elements;
  • All methods or plug-ins must end with a semicolon to avoid problems (to be more secure, you can add a semicolon at the head of the plug-in);
  • The plug-in should return a jQuery object to ensure chainable operations;
  • Avoid using $ inside the plug-in. If you want to use it, use a closure to pass jQuery in, so that the plug-in will continue to use $ as an alias for jQuery.
;(function($){//这里将$符作为匿名函数的形参
/*在此处编写代码,可使用$作为jQuery的缩写别名*/
})(jQuery);//这里将jQuery作为实参传递给匿名函数了

3. Write a plug-in

Suppose our plug-in requirement is to implement a drop-down menu, display the corresponding drop-down list when the element is moved in, and retract it when it is moved out. And you can set the text color when it is expanded.

According to convention, when we write plug-ins, we can have some constraints on the html structure. Now assume that our page has the following HTML structure:

<ul class="list">
 <li>导航列表1
  <ul class="nav">
   <li>导航列表1</li>
   <li>导航列表2</li>
   <li>导航列表3</li>
   <li>导航列表4</li>
   <li>导航列表5</li>
   <li>导航列表6</li>
  </ul>
 </li>
 <li>导航列表2
  <ul class="nav">
   <li>导航列表1</li>
   <li>导航列表2</li>
   <li>导航列表3</li>
   <li>导航列表4</li>
   <li>导航列表5</li>
   <li>导航列表6</li>
  </ul>
 </li>
</ul>
<!-- 默认已经引入jquery -->

在这里,我们就对我们的插件实现效果有了第一个要求,必须在 对于需要hover展现的元素 内部下面建立 ul 列表,且 className 必须为 nav 。(插件内部都是根据该条件来做文章)

下面就可以开始编写我们的插件了。保存为 jQuery.nav.js ,(符合上面所说的要求,默认已经导入)

;(function($){
 $.extend({ //插件定义在全局方法上
  "nav" : function (color){//传参,这里只是抛砖引玉,在您编写的时候,参数选项可以更加丰富,例如传入json对象等等
   $('.nav').css({//对展开的下拉列表设置样式,此处在下面进行详细说明
    "list-style" : "none",
    "margin" : 0,
    "padding" : 0,
    "display" : "none",
    "color":color//由用户控制hover时,展现出来列表的文字颜色
   });
   $('.nav').parent().hover(//这里用到了.nav的父节点(就是hover到的元素)
    //因为我们只能在插件要求的范围内进行设定,若是使用了外部的选择器,就违背了这个原则
    function (){
     $(this).find(".nav").stop().slideDown("normal");//注意我们在这里使用了jquery的动画方法
    },function (){
     $(this).find(".nav").stop().slideUp("normal");//注意stop()的使用,不然会有类似手风琴效果的出现,但那并不是我们需要的
    });
  }
 });
})(jQuery);

注意:这里使用css方法只是为了方便,在真实插件编写过程中,若存在如此大量的css样式编写时,推荐在外部定义css样式,例如可改写为:

插件依赖的css,需和插件一起导入html中

.hover{/*插件必须样式*/
 list-style: none;
 margin:0;
 padding: 0;
 display: none;
}

在插件内部修改。

$('.nav').addClass("hover");//将CSS与jQuery分离开来
$('.nav').css("color",color);//存在用户设置时启用,不存在就不用了(进行判断)

刚刚说的都是插件的js文件,最后要起到效果,别忘了页面的js中加上那么一句话(当前插件定义在全局方法上)

$(function (){
 $.nav("#999");//调用插件实现的全局方法,并且设置其展现背景颜色为#999。
});

就这样,我们的全局插件就编写,而且调用完成了,在你的页面刷新看看,是不是已经有了效果呢?

但是,因为我们的方法定义在全局上,现在只要页面中出现了我们插件所规定的结构,就会存在hover展现效果,但是有时我们往往想要的不是这样,我们希望它在局部,在我指定的元素调用。所以我们需要对其进行一些改造,让其变成局部方法,其实也很简单:

;(function($){
 $.fn.extend({//定义为局部方法
  "nav" : function (color){
   $(this).find('.nav').addClass('hover');//上面已经说过了,此时this指向调用该方法的元素
   $(this).find('.nav').css("color",color);//在当前元素下,增加了一次find筛选,实现在对应的元素中执行。
   $(this).find('.nav').parent().hover(
    function (){
     $(this).find(".nav").stop().slideDown("normal");
    },function (){
     $(this).find(".nav").stop().slideUp("normal");
    });
   return this;//返回当前的对象
  }
 });
})(jQuery);

我们去刷新一下浏览器。你会发现,咦,怎么没效果? 当然因为原来的代码是直接在全局调用的,现在变成局部方法了,显然就不能这样做了,需要做一点改变:

我这里就不贴html代码了,但是希望您在实践时能把上面的html代码在其下复制几份,以达到思考其实现的效果

$(function (){//这里的eq(0)代表只对第一份起到效果,复制后的没有效果。
 //(你可以把上面的find筛选删除之后再试试,您会发现,他又对余下的几份起效果了)
 $(".list").eq(0).nav("red");//调用局部方法
});

现在回过头再把我们写的插件代码对应上面写的 插件编写的要点 ,思考一下,我们还有哪些没有做到?就会发现,基本已经能对应上了。现在我们就完成了一个下拉菜单的插件。

其实编写插件并不难,最主要的是在我们编写插件的时候,一定要时刻注意这样的要点,每一个细节都遵循在大家实践过程中总结出来的最佳实现,才能自定义实现一个良好的插件。

代码首先是写个人看的,再然后才是给机器看的。

Statement
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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.