2014-12-26 67 views
0

有一個項目ID gameIds[i]_container的列表顯示在FOR循環中。在這些顯示沒有問題。Javascript for Loop回撥

我希望控制檯記錄項目的gameIds[i]該項目單擊。我相信這應該是用回調完成的,但是當點擊項目時目前沒有發生。

請幫忙!

代碼:

//CLICKING ON GAMES 
//Active Game - bring user to game 
//Newly Invited Game - ask user to accept invite, then either bring to game or delete from players list 
//Rematch Game - recreate previous game 

//Function 
function gameAccess(i) { 
    //REMATCH GAME 
     if (currentRound[i] == roundWinners[i].length && currentRound[i] != 0 && currentRound[i] == numberOfRounds[i]){ 
      console.log("You clicked " + gameIds[i]); 
     } 
     //NEWLY INVITED GAME 
     if (currentRound[i] == 0 && currentUserId != creator[i]) { 
      console.log("You clicked " + gameIds[i]); 
     } 
     //ACTIVE GAME 
     else{ 
      console.log("You clicked " + gameIds[i]); 
     } 
} 

//Callback 
function gameAccessCallback(i){ 
    return function(){ 
     gameAccess(i); 
    }; 
} 

//Iterate Through 
for (i = 0; i < numberOf; i++) { 
    document.getElementById(gameIds[i] + "_container ").click(gameAccessCallback(i)); 
}; 
+0

你的問題中提到'gameIds [I] _container',但這不是有效的JavaScript。 – jfriend00

+0

類似問題:http://stackoverflow.com/questions/8623088/undefined-indexes-in-array-after-asynchronous-requests/8623120#8623120和http://stackoverflow.com/questions/18880895/why-when- i-add-a-bunch-of-event-listeners-in-a-loop-does-every-element-trigger/18880964#18880964和http://stackoverflow.com/questions/21487187/why-is-the- loop-assigning-a-reference-of-the-last-index-element-to/21487254#21487254和http://stackoverflow.com/questions/22273839/proper-code-for-a-for-loop-in- javascript/22273973#22273973 – jfriend00

+1

我不認爲這是重複的。他的'gameAccessCallback'函數解決了這些重複中的問題。他只是沒有正確地約束事件。 –

回答

3

這裏的問題是,你正在做document.getElementById(...).click()。 DOMElements沒有click方法! jQuery的確如此,但它看起來並不像你在這裏使用的那樣。

試試這個:

for (i = 0; i < numberOf; i++) { 
    document.getElementById(gameIds[i] + "_container ").addEventListener('click', gameAccessCallback(i)); 
}