今天處理table表格下的<tr>中的<td>標籤中幾個按鈕點擊事件,三個按鈕分別要實現置頂,取消置頂,刪除操做。其中EditRequest()函數是寫好的ajax方法,一開始我是這麼寫的:javascript
$('.cancel-top').click(function(){ var pid = $(this).parents('tr').find(".pid").text(); if(confirm("肯定要取消置頂嗎?")){ EditRequest(pid,'not_top'); } }); $('.to-top').click(function(){ var pid = $(this).parents('tr').find(".pid").text(); if(confirm("肯定要置頂此主題帖嗎?")){ EditRequest(pid,'top'); } }); $('.del-post').click(function(){ var pid = $(this).parents('tr').find(".pid").text(); var _this = $(this); if(confirm("肯定要刪除此主題帖嗎?")){ EditRequest(pid,'del',_this); } });
那麼問題來了,好像三個事件函數都差很少,這樣寫的話產生了大量重複代碼,並不以爲它足夠優雅,因而決定改寫它:java
1 var config = [ 2 {'classNm':'cancel-top','msg':'取消置頂','type':'not_top'}, 3 {'classNm':'to-top','msg':'置頂此帖','type':'top'}, 4 {'classNm':'del-post','msg':'刪除此帖','type':'del'}, 5 ]; 6 for(var i=0;i<3;i++){ 7 $('.'+config[i].classNm).click(function(){ 8 var _this = $(this), 9 pid = $(this).parents('tr').find(".pid").text(); 10 if(confirm("肯定要"+config[i].msg+"嗎?")){ 11 EditRequest(pid,config[i].type,_this); 12 } 13 }) 14 };
顯然click事件處理函數內部是獲取的i值老是3,此時我想大聲呵呵。說來慚愧,我並無深刻理解javascript中的做用域問題。腦補了一下後,將for語句改寫以下:ajax
1 for(var i=0;i<3;i++){ 2 (function(i){ 3 $('.'+config[i].classNm).click(function(){ 4 var _this = $(this), 5 pid = $(this).parents('tr').find(".pid").text(); 6 if(confirm("肯定要"+config[i].msg+"嗎?")){ 7 EditRequest(pid,config[i].type,_this); 8 } 9 }) 10 })(i); 11 };
使用閉包就能夠巧妙地解決問題,可是總以爲jQuery有本身的辦法而不是使用難以理解的麻煩的閉包。因而又腦補了一下後,改寫以下:閉包
1 for(var i=0;i<3;i++){ 2 $('.'+config[i].classNm).click({index:i},function(e){ 3 var _this = $(this), 4 pid = $(this).parents('tr').find(".pid").text(); 5 if(confirm("肯定要"+config[e.data.index].msg+"嗎?")){ 6 EditRequest(pid,config[e.data.index].type,_this); 7 } 8 }) 9 };
jQuery中的事件處理函數均可以自帶event參數的,每每都是默認的一些參數。固然也能夠手動添加一些參數到它的data屬性裏面,正是利用了這一點達到了個人目的。忽然就精簡了,是否是又進步了一點點了呢?!哈哈哈…函數