2012-03-10 83 views
0

我正在使用jQuery和我使用Slim構建的API創建移動應用程序。基於數組的動態偵聽器

我的總體目標是創建一個按鈕列表,當單擊它時將調用具有適當參數的函數。

我成功將我的請求發送到slim,獲取用戶列表並將結果存儲在全局User對象數組中。

接下來,我通過數組附加html到文檔來顯示按鈕。同時,我添加了一個點擊監聽器。聽衆得到補充,但不像我期望的那樣。

用戶是具有全局作用域的用戶對象數組。用戶對象可以歸爲[{「name」:「用戶名」}]。

也可能是我在回電時這樣做的事實。

$.getJSON(url, function(data){ 
    for(i=0;i<data.length;i++) 
    { 
     var u = new User(); 
     u.name = data[i]['name']; 
    } 
}) 
//The success handler DOES get called. 
.success(function() { 
    for(var i=0; i<users.length; i++) 
    { 
     //this part works. users[i] is accessed as expected. 
     var html_string = '<li>'+users[i].name+'</li>'; 

     $("#myUL").append(html_string); 
     $("#myUL li:last").click(function(){ 
      //logs undefined 
      console.log(users[i].name); 

      //Handle the event 
      eventHandleFunction() 
     }); 
    } 
}) 

我不夠好,精通一般要知道我在做什麼不屬於最佳實踐編程,但我在JavaScript這樣文盲,我不知道解決的正確方法它。除了回答問題之外,我真的很感謝任何花時間指點我有用資源的人。

更新:閱讀關於使用委託來分配處理程序的答案後,我已經更新了一下我的代碼。現在看起來像這樣。注意:我只是沒有更新上面的代碼才能得到原始問題的「爲什麼」部分的答案。

$("#myUL").delegate("li","click",function(){ 
      //sets the attribute name of the global var user 
    user.name = $(this).text(); 
      //lets see what user.name is now. Oh, look. It's what i expect 
    alert(user.name); 
    //do whatever else i want to do here. 
}); 

//This json request is now (i believe) entirely unnecessary to answer the question. 
$.getJSON(url, function(data){ 
    for(i=0;i<data.length;i++) 
    { 
     var u = new User(); 
     u.name = data[i]['name']; 
    } 
}) 
//The success handler DOES get called. 
.success(function() { 
    //No longer relevant 
}) 

回答

1

,你可以,如果你正在使用jQuery版本1.7+然後使用delegate

$("#myUL").delegate("li:last","click",function(){ 

//event handler code here 
}); 

這樣你沒有明確的附加Click事件處理程序的每一個在DOM

動態添加li您可以使用.on方法,如

$("#myUL").on("click","li:last",function(){ 

//event handler code here 
}); 

了爲什麼部分

我看到的原因是範圍

for(var i=0; i<users.length; i++) 
    {  

     var html_string = '<li>'+users[i].name+'</li>'; 

     $("#myUL").append(html_string); 

     $("#myUL li:last").click(function(){ 
      //logs undefined BECAUSE i is undefined inside the click handler 
      console.log(users[i].name); 
      //Handle the event 
      eventHandleFunction() 
     }); 
    } 
+0

這引起了我重寫一段代碼,但一旦我做了(和RTFM上代表)我得到了它的工作。我的問題的'爲什麼'部分的任何輸入? – Jake 2012-03-10 13:47:58

+0

@Jake我更新了答案閱讀更新部分中的評論 – Rafay 2012-03-10 13:55:58

0
for(var i=0; i<users.length; i++) { 
    var numb = i, 
     html_string = '<li>'+users[numb].name+'</li>'; 

    $("#myUL").append(html_string); 

    $("#myUL li:last").click(function(){ 
     console.log(users[numb].name); 

     eventHandleFunction() 
    }); 
} 
+0

可以說用戶是數組(「a」,「b」,「c」)。然後用for(var i = 0; i Jake 2012-03-10 13:21:53

+0

@Jake - 改變我的答案,試試吧? – adeneo 2012-03-10 14:04:31