jQuery插件扩展测试实例

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>JQquery扩展插件测试</title> <script type = "text/javascript" src="https://www.jb51.net/jquery-1.7.2.min.js"> </script> <style type = "text/css"> .a{ background:#ccc; } .b{ background:#555; } </style> <script type = "text/javascript"> //1.对象级别的扩展 jQuery.fn是jQuery.prototype的别名 // 注意:在对象方法内,关键字this引用的是一个jQuery对象,但在每次调用的.each()方法中,this引用的是一个dom元素(所以each内部要用jQuery包装this,而在return后面,直接调用jQuery对方法.each()) (function($){ $.fn.toggleClass = function(options){ return this.each(function(){ var opts = $.extend({},$.fn.toggleClass.defaults,options); var $element = $(this); if($element.hasClass(opts.class1)){ $element.removeClass(opts.class1).addClass(opts.class2); }else if($element.hasClass(opts.class2)){ $element.removeClass(opts.class2).addClass(opts.class1); } }) } $.fn.toggleClass.defaults = { class1:"", class2:"" } $.fn.setBorder = function(){ return this.each(function(){ $(this).css("border","1px solid red"); }) } })(jQuery); $(function(){ var opts = { class1:"a", class2:"b" } $("h1").click(function(){ $("h1").toggleClass(opts).setBorder(); }) }) //2.类级别的扩展 //1).直接添加:为jQuery对象添加全局函数 jQuery.sum = function(array){ var total = 0; jQuery.each(array,function(idx,num){ total += num; }) return total; } //2).用extend添加: jQuery.extend({ fn1:function(){}, fn2:function(){} }) </script> </head> <body> <h1 id = "h1" class = "a">JQuery扩展测试</h1> </body> </html>

更多关于jQuery相关内容感兴趣的读者可查看本站专题:《jQuery扩展技巧总结》、《jQuery常用插件及用法总结》、《jQuery拖拽特效与技巧总结》、《jQuery表格(table)操作技巧汇总》、《jquery中Ajax用法总结》、《jQuery常见经典特效汇总》、《jQuery动画与特效用法总结》及《jquery选择器用法总结

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wzsjxx.html