jquery插件的编写

来源:互联网 发布:站内搜索优化方案 编辑:程序博客网 时间:2024/05/21 07:52

以下是一个编写基于jquery的插件实例:

<!DOCTYPE html><html><head><title>jquery自定义插件</title><script type="text/javascript" src="../js/jquery_172.js"></script></head><body><div><script type="text/javascript">console.log("****** 一般形式的function定义及调用 ******");// 定义function func1(arg){console.log(arg);}// 调用func1("hi,func demo1")console.log("****** 匿名函数的定义及调用 ******");// 定义var afunc1 = function(arg){console.log(arg);}// 调用afunc1("hi,anonymous func");console.log("****** 匿名函数的定义,同时调用 ******");(function (arg){console.log(arg);})("hi,go anonymous func");// 后接参数,会直接调用console.log("****** 匿名函数达成闭包效果 ******");var afunc2 = function(index){return function (){// index被操作,afunc2未被销毁,所以index会被记录console.log(index++);}}(1);afunc2();// 1afunc2();// 2// 书写jquery插件时,常用的$.extend(function ($){// 自定义一个jquery全局function$.extend({hi: function(){console.log("hi");}});// 将hi方法合并到jquery的对象中去$.fn.extend({hi: function(){console.log($(this).html());}});})(jQuery);// 一个插件例子var data1 = "[{id:'001',name:'xwl',age:20},{id:'002',name:'will',age:22}]";var data2 = "[{id:'003',name:'lwx',age:21},{id:'004',name:'ci',age:8}]";(function ($){// 默认设置var defaults = {title: 'default title',};// 为jquery对象新增mytable方法$.fn.mytable = function (options){options = $.extend(defaults,options);// 合并设置var data = eval("("+options.data+")");$(this).append("<table width='100%' border='0' cellspacing='0' cellpadding='0'></table>");$("table",this).append("<tr><td colspan='3'>"+options.title+"</td></tr>");var o = this;$.each(data,function (k,v){// 遍历传入的data数组$("table",o).append("<tr><td>"+v.id+"</td><td>"+v.name+"</td><td>"+v.age+"</td></tr>");});return this;}})(jQuery);$(document).ready(function(){// 调用jquery对象上的自定义方法$("#div1").mytable({title: 'hi,mytable title',data: data1});console.log("****** 调用jquery自定义方法 ******");$.hi();console.log("****** 调用jquery对象上的自定义方法 ******");$("#div1").hi();});</script><div id="div1"></div><div id="div2"></div></div></body></script>


0 0
原创粉丝点击