2014-12-26 68 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)); 
}