通过这两篇文章:
http://www.cnblogs.com/fromearth/archive/2009/07/08/1519054.html
http://www.iteye.com/topic/545971
对jQuery插件的开发有了一个初步的认识,下面是自己在尝试写一个简单的插件过程中的一些问题的记录。
1、定义插件方法
(function($) { $.fn.scrolload = function(options) { debug("this is a plugin-method"); }; $.fn.renderHtml = function(datas, options) { }; function debug(obj) { if (window.console && window.console.log) { window.console.log(obj); } } })(jQuery);
如上,这里定义了两个插件方法。我们就可以通过实例化的jquery对象进行访问:
页面内容:
<input type="button" id="zbtn" value="确定" />
调用插件方法:
$(function() { $("#zbtn").bind("click", function() { $(this).scrolload(); }); });
我们可以在firebug下看到输出信息
2、私有方法
当然,在上面的例子中,多了一个函数debug,是在插件方法scrolload 中去调用,如果直接在实例的jquery对象中调用呢:
$("#zbtn").bind("click", function() { $(this).debug("zz"); });
这里error: $(this).debug is not a function 可见这里的debug就是该插件中的一个私有方法
3、参数合并
在插件开发中经常会有在调用函数时传入参数,以及方法本身会默认维护一套参数。需要在方法的运行中修改相应的设置。在jQuery中主要也是用extend的方法来合并参数,见
http://mj4d.iteye.com/blog/1569183
以下是renderHtml默认设置:
$.fn.renderHtml = function(datas, options) { options = $.extend(true, $.fn.renderHtml.defaults, options); debug(options.name+" - "+options.age); }; $.fn.renderHtml.defaults = { checkBox : false, age : 20 };
调用该方法:
$("#zbtn").bind("click", function() { $(this).renderHtml("", { name : "aaa" }); });
4、以下是自己写的一个简陋的将数据生产html代码的插件方法:
考虑传入的数据为json格式的数组,将传入的数据生产table内的元素,当然需要支持class。以及用户可回调生产自定义的html内容
$.fn.renderHtml = function(datas, options) { options = $.extend(true, $.fn.renderHtml.defaults, options); var cl = options.columns; var result = ""; if (datas && datas.constructor == Array) { for ( var i = 0, j = datas.length; i < j; i++) { data = datas[i]; // var tr = "<tr>"; for ( var n = 0, m = cl.length; n < m; n++) { // style: var tdStyle = ""; tdStyle += "text-align:" + (cl[n].align || "center") + ";"; if (cl[n].width) { tdStyle += "width:" + cl[n].width + ";"; } tdStyle = "style:\"" + tdStyle + "\""; var td = "<td " + tdStyle + ">"; // content if (cl[n].callBack && cl[n].callBack.constructor == Function) { td += cl[n].callBack.call(this, data[cl[n].dataIndex], data, i); } else { td += data[cl[n].dataIndex]; } tr += td + "</td>"; } tr += "</tr>"; result += tr; } } return "<table>" + result + "</table>"; }; $.fn.renderHtml.defaults = { checkBox : false, age : 20 };
以下是调用的代码:
$(function() { var data = [ { "age" : 24, "name" : "robin", "desc" : "aa" }, { "age" : 23, "name" : "jack", "desc" : "bb" }, { "age" : 23, "name" : "rose", "desc" : "ccc" }, { "age" : 24, "name" : "shine", "desc" : "ddd" } ]; $("#zbtn").bind("click", function() { $("#contentDiv").html($(this).renderHtml(data, { columns : [ { align : "center", width : "40px", dataIndex : 'age', //v:当前元素值、d:当前对象、i:序号 callBack: function(v,d,i){ return "<a href=\"javascript:alert('"+d.age+"')\">"+v+"</a>"; } }, { width : "230px", dataIndex : 'name' }, { align : "right", width : "40px", dataIndex : 'desc' } ], age:23 })) }); });
在生成的table中,age列是有超链接,同时点击时弹出该值