Steffan Harris
Steffan Harris

Reputation: 9326

Match various Ids against a index within a loop

I'm trying to translate this line of Javascript code to Jquery. The problem i'm having is how do I get i to be incorporated in the jquery statement

for (var i = 0; i < game.BOARD_SIZE; i++)
        document.getElementById("pos" + i).addEventListener("click", game.MakeMove, false);

I know that I want to use the click() function, but my problem is incorporating the index.

Upvotes: 1

Views: 42

Answers (1)

Didier Ghys
Didier Ghys

Reputation: 30666

To get an element by ID in jquery, use the selector #id. It can be a constructed string that you pass to the jquery function, like this:

for (var i = 0; i < game.BOARD_SIZE; i++) {
    $('#pos' + i).click(function(e) {
        game.MakeMove();
    }
}

I'm not sure about the last parameter of .addEventListener() (true/false) though.
Maybe you should use e.stopPropagation() after the call to MakeMove() to fully translate your javascript addEventListener call.

Further reading:

Upvotes: 2

Related Questions