I am working on a simple app that simulates a chess board. Therefore I have a table with 64 squares. I would like to bind event handlers for each square by writing a single function that goes through a loop instead of writing things out 64 times. EDIT: Please note I want the handlers to return a numeric value to indicate which div was clicked. I don't need the handlers to return the content of the divs. Here is a simplified version given two clickable divs:
<div id="div0">A box</div>
<div id="div1">Another box</div>
<div id="say"></div>
and the javascript code:
$("#say").append("Which div are you going to click? ");
function clicky() {
var i = 0;
while (i < 2) {
$("#div" + i).on("click", function () {
$("#say").append("div" + i);
});
i++;
}
}
clicky();
Here is the jsfiddle.
The function almost works, that is, it binds to both divs, but it binds the same (wrong) handler to both of them. Not sure how to fix this.