寫這篇文章主要是對本身之前學習jquery插件的總結。如今組件化開發,以vuejs 、 reactjs 、angular 爲表明的庫或框架讓web組件化開發逐漸推廣起來。下面是我用jquery寫的一款簡易的提示框組件。雖然沒有遵照mvc寫法,但也是很實用。html
有時用戶執行某個操做時,須要彈出提示框讓用戶肯定執行某個回調函數,這樣就有效的避免用戶因操做失誤執行不應執行的操做。vue
/** * Created by helti on 2017/2/16 0016. */ !(function(window,$,undefined){ var htmls={ 'popbg':'<div class="pop-bg"></div>', 'pwraper':'<div class="p-wraper"></div>', 'popheader':'<div class="p-heaer"></div>', 'popdes':'<p class="p-des"></p>', 'palert':'<div class="p-alert"><button id="btn-ok">肯定</button></div>', 'pconfim':'<div class="p-confim"><button class="btn-ok">肯定</button> <button class="btn-cancel">取消</button></div>' }; var winpop=function(opt,callback){ var defaults={ headercon:'', popdes:'' } this.options= $.extend({},defaults,opt); this.$body=$('body'); //背景 this.$popbg=$(htmls.popbg); //pop父容器 this.$wraper=$(htmls.pwraper); if(callback !='undefined'){ if(typeof callback == 'function'){ this.callback=callback; } }else{ throw new Error ('callback need function') } }; winpop.prototype={ /* alert 或者 confim */ createdom:function(ele){ var $popheaer=$(htmls.popheader).text(this.options.headercon); var $contenthtml=$(htmls.popdes).text(this.options.popdes); // $palert=$(htmls.palert); this.$wraper.append($popheaer).append($contenthtml).append(ele); this.$body.append(this.$popbg).append(this.$wraper); // this.callback(); // console.log(this.callback); }, okclick:function(){ //確認按鈕執行回調函數 this.callback(); }, eventclick:function(){ var that=this; that.$wraper.find("#btn-ok").on("click",function(){ that.remove(); that.okclick(); }) //只經過事件委託綁定一次,若是用on綁定,由於doument沒法刪除,致使事件一直存在 /* $(document).one("click","#btn-ok",function(){ that.remove(); that.okclick(); });*/ that.$wraper.find(".btn-ok").on("click",function(){ that.remove(); that.okclick(); }) /* $(document).one("click",".btn-ok",function(){ that.remove(); that.okclick() });*/ that.$wraper.find(".btn-cancel").on("click",function(){ that.remove(); }) }, alertpop:function(){ var $palert=$(htmls.palert); this.createdom($palert); this.eventclick(); }, confimpop:function(){ var $pconfim=$(htmls.pconfim); this.createdom($pconfim); this.eventclick(); }, remove:function(){ this.$wraper.empty().remove(); this.$popbg.empty().remove(); } }; window.winpop=winpop; }(window,jQuery));
咱們都知道動態生成的dom元素,要給它綁定事件時,必須給予事件委託,一般咱們委託給document.react
//這裏不該該用on $(document).one("click","#btn-ok",function(){ that.remove(); that.okclick(); });
可是咱們委託給document時會出現一個問題,就是但你再次觸發按鈕時,原來綁定的事件不會銷燬。由於document不能刪除。那麼用one呢?咱們只讓它執行一次。你們能夠試下。jquery
最終我使用了git
that.$wraper.find(".btn-cancel").on("click",function(){ that.remove(); })
這樣就避免了事件不被銷燬。從而累計事件的bug.github
github源碼web