Running a for loop to create a number of divs with ID at1, at2, at3, etc.
function maketiles() {
for (i = 1; i < 7; i++) {
var div = document.createElement('div');
div.id = "at" + i;
$("tiles").appendChild(div);
}
}
Then I addEventListener to each div so they can be clicked to call another function and pass a unique number (same number as their ID) to said function.
If I add them separately like this:
$("at1").addEventListener("click", function () { build(1) });
$("at2").addEventListener("click", function () { build(2) });
$("at3").addEventListener("click", function () { build(3) });
$("at4").addEventListener("click", function () { build(4) });
$("at5").addEventListener("click", function () { build(5) });
$("at6").addEventListener("click", function () { build(6) });
It works fine. But it would be more efficient to just add that one line during the loop, like this:
function maketiles() {
for (i = 1; i < 7; i++) {
var div = document.createElement('div');
div.id = "at" + i;
$("altartiles").appendChild(div);
$(div.id).addEventListener("click", function () { build(i) });
}
Yet that doesn't work. It seems that the problem is the i variable. It doesn't turn into the 1, 2, 3.. that it contains. Is there any way to make this work?
PS In case it wasn't clear, I have
var $ = function (id) { return document.getElementById(id); };
set, just like jquery.