2013-02-20 36 views
1

我寫了JS函數,它必須綁定它生成的按鈕,這取決於數組中的值。 但它給了我最後的價值。我讀到我必須使用閉包,我做了,而且我仍然無法將它們綁定到正確的位置! 我還是一個初學者 我瞭解封,給我的想法,但仍然不知道我失蹤不能使用Closure權利

function addNewServices(newServicesArray){ 
    var j=0; var x; 
    for (i in newServicesArray){ 
     var html=''; 

     html='<div style="width: 33%; float: leftt"><a href="#" data-role="button" data-icon="home" id="btn-'+newServicesArray[j].servicename+'" value="'+newServicesArray[j].servicename+'" class="ui-btn-up-c">'+newServicesArray[j].servicename+'</a></div>'; 
     $("#main-menu").append(html); 


     $('#btn-'+newServicesArray[j].servicename).bind('click', function(){bindThis(j)}); 
     j++; 
    } 

    var bindThis = function(j) { 
     return function() { 
      alert(j); // gives 2 always 
      alert(newServicesArray[j].servicename); 
     }; 
    }; 
} 
+1

使用jQuery的'$ .each'迭代,您可以更輕鬆...... – elclanrs 2013-02-20 09:09:01

+0

你不應該申報'bindThis'內循環。爲什麼你聲明x並且從不使用它? – fragmentedreality 2013-02-20 09:16:10

+0

@fragmentedreality實際上,bindThis在循環內部是* not *聲明的。 – Christoph 2013-02-20 09:28:42

回答

1

你不必綁定在點擊一個循環...你可以通過在函數$(this)獲得點擊refrence ..

使得它作爲簡單的,因爲我可以..

function addNewServices(newServicesArray){ 
    var j=0; 
    for (i in newServicesArray){ 
     var html=''; 

     html='<div style="width: 33%; float: left"><a href="#" data-role="button" data-icon="home" id="btn-'+newServicesArray[j].servicename+'" value="'+newServicesArray[j].servicename+'" class="ui-btn-up-c">'+newServicesArray[j].servicename+'</a></div>'; 

     $("#main-menu").append(html); 


    } 
} 

$(function(){ 
    $(document).on('click','a[id^="btn-"]',function(){ 
     var $this = $(this); 
     alert($this.attr('value')); 
    }); 
}); 
1

因爲你有

function(){bindThis(j)} 

它得到後來被稱爲當j的值爲2

你只需要

bindThis(j) 

都會調用不同取值

+2

這是一個無關的錯誤... – Christoph 2013-02-20 09:15:42

1

Closure只是函數從外部範圍訪問變量的方式。這裏的關鍵詞是變量 - 變量可能會改變,如果您之後訪問它(點擊),您將訪問它的更高版本。

所以,無論如何,你需要的j該關聯存儲與j個按鈕。感謝jQuery,bind方法已經有一個功能:second parameter,eventData是一些用戶數據,它將被傳遞給事件處理函數。

因此,改變這種:

(..).bind('click',function(){bindThis(j)}); 

這樣:

(..).bind('click', j, bindThis); 

...應該*工作。請注意,我們不需要創建任何包裝函數。我們只需將bindThis函數本身傳遞給bind,並告訴bind它將在調用它時將j傳遞給它。

(*) - 尚未測試