【jQuery 提高】 创建自己的jQuery plugin
有些时候当你写了一个很有用的功能,并且希望这个功能能够很方便的用到其他的项目中去,这时候你可以自己创建一个jQuery plugin.
先看一行jQuery的代码:
$( "a" ).css( "color", "red" );
这是一个标准的jQuery的代码,方便,简洁,你知道如何使用,但是你知道他是如何实现的吗?
无论什么时候你使用$符号去调用去选择元素,实质上都会返回一个jQuery的对象。
这个对象包含了所有你所用过的jQuery方法, 比如.css(), .click()等等。而这个jQuery对象是通过$.fn对象来获得所有方法的,如果我们想自己创建jQuery函数,我们也需要用到它。
一个简单的例子:
比如把links都变成绿色的。
$.fn.greenfiy = function(){ this.css('color':'green'); } $("a").greenfiy(); // Make all the links green
注意:在代码中我们使用this.css(), 而不是$(this).css(), 这是因为我们的greenfiy()和css()都是属于同一个object的。
链式:
在平时使用jQuery的时候,注意到jQuery最大的一个便捷的地方就是可以使用链式编程, 例如$("p").css('color': 'red').fadeOut();
但是上面的代码还不能实现这样的链式编程,因此我们需要做修改。
$.fn.greenify = function() { this.css( "color", "green" ); return this; // Add this line } $( "a" ).greenify().addClass( "greenified" );
我们返回了this对象,从而使得后继的.fadeOut()等方法可以继续作用于这个对象。
注意:想这样的链式编程不适用与像$.trim()
防止$变量名冲突和添加作用域:
在Javascrip中$符号使用的频率很高 , 比如你代码中存在这样的代码:
function $(id){ return document.getElementById(id); }
如果使用我们之前所说的方法去添加jQuery的插件,可想而知会报错,因为你自己定义的$方法中并没有.css, .fadeOut这样的成员方法。
为了和其他插架兼容,并且我们得以继续使用$这个符号,我们可以这样做: Immediately Invoked Function
(function ( $ ) { $.fn.greenify = function() { this.css( "color", "green" ); return this; }; $.ltrim = function( str ) { return str.replace( /^\s+/, "" ); }; $.rtrim = function( str ) { return str.replace( /\s+$/, "" ); }; }( jQuery ));
这样做的另一个主要的目的是我们可以在这个作用域中添加私有的变量,比如我们定义一个默认的颜色:
(function ( $ ) { var shade = "#556b2f"; $.fn.greenify = function() { this.css( "color", shade ); return this; }; }( jQuery ));
优化作用域中的代码:
最好在你的作用域中仅写一个$.fn方法,这样可以你的代码被其他插件重写。
所以可以将下面的代码:
(function( $ ) { $.fn.openPopup = function() { // Open popup code. }; $.fn.closePopup = function() { // Close popup code. }; }( jQuery ));
改写为:
(function( $ ) { $.fn.popup = function( action ) { if ( action === "open") { // Open popup code. } if ( action === "close" ) { // Close popup code. } }; }( jQuery ));
使用.each()方法:
如果你想对多个元素同时进行操作,那可以使用.each(),而不是单独使用this,推荐使用这种方法。
$.fn.myNewPlugin = function() { return this.each(function() { // Do something to each element here. }); };
接受额外的Options:
当你的插件功能变得更加复杂的时候,你可以使用接收额外的Options参数。
(function ( $ ) { $.fn.greenify = function( options ) { // This is the easiest way to have default options. var settings = $.extend({ // These are the defaults. color: "#556b2f", backgroundColor: "white" }, options ); // Greenify the collection based on the settings variable. return this.css({ color: settings.color, backgroundColor: settings.backgroundColor }); }; }( jQuery ));
整合所有:
<!DOCTYPE html> <html> <head> <script type="text/javascript" src="http://cs.uef.fi/o-mopsi/js/jquery/jquery-1.9.1.min.js"></script> </head> <body> <div id="div" style="width: 500px; height: 500px; background: grey;">Make it green</div> <script> $("#div").click(function(){ /* $(this).greenfiy(); //Use default settings //one way: options = { 'color': 'green', 'backgroundColor':'yellow' }; $(this).greenfiy(options); */ //second way $(this).greenfiy({'color':'green', 'backgroundColor':'yellow'}); }); (function(){ $.fn.greenfiy = function(options){ var settings = $.extend({ 'color':'#556f2b', 'backgroundColor': 'white' }, options); return this.each(function(){ $(this).css({ 'color': settings.color, 'backgroundColor': settings.backgroundColor }); }); } }(jQuery)); </script> </body> </html>
现在就可以使用自己的插件了!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具