Javascript FOR循环回调

时间:2014-12-26 21:02:02

标签: javascript loops callback

gameIds[i]_container循环中显示的商品ID FOR列表。在这些显示没有问题。

我希望控制台在项目点击时记录项目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));
};

1 个答案:

答案 0 :(得分:3)

这里的问题是你正在做document.getElementById(...).click()。 DOMElements没有click方法! jQuery可以,但它看起来并不像你在这里使用它。

试试这个:

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