【前端】jQurey Plugin
; (function ($, window, document, undefined) { "use strict"; var defaults = { name: "xiaoxiao", age: 18 }; function ShowPepleInfo($ele,options,callback) { this.$ele = $ele; this.options = options = $.extend(defaults, options || {}); this.callback = callback || {};//若为undefined则新建callback对象 this.init(); } ShowPepleInfo.prototype = { constructor: ShowPepleInfo, init: function () { this.renderHtml(); this.bindEvent(); }, renderHtml: function () { var options = this.options; var html = []; html.push('<div class="info">'); html.push('<p>姓名:' + options.name + '</p>'); html.push('<p>年龄:' + options.age + '</p>'); html.push('</div>'); this.$ele.html(html.join("")); }, bindEvent: function () { var that = this; that.$ele.delegate("p", "click", function () {//直接把事件绑定在父元素$ele alert($(this).html()); if (typeof that.callback == 'function') { that.callback($(this).html());//执行回调函数 } }); }, //others... } $.fn.showPeopleInfo = function(options,callback){ options = $.extend(defaults, options || {}); return new ShowPepleInfo($(this), options, callback); } })(jQuery)
//使用
$("#main").showPeopleInfo({ name: "dada", age: 20 }, function (e) { alert(e); });
//不用立即执行函数包括
var show = new ShowPepleInfo($("#main"), { name: "dada", age: 20 }, function (e) { alert(e); });
alert(show.options.name);