I'm having this problem in JS - which is not my native language at all. I have declared a global variable var divID = 0; which just is a unique number. There is a button on my HTML page that, when you click it, will add a bunch of stuff to the DOM.
Something like:
function addStuff() {
divID++;
newDiv = document.createElement("div");
newDiv.id = "div" + divID;
// Create a bunch more nodes under newDiv
// including some button with id: "newButton" + divID
document.getElementById("someDiv").appendChild(newDiv);
$("#newButton" + divID).click(function() {
// do stuff with child nodes of "newDiv" + divID
});
}
I hope this makes sense. Basically, each time addStuff() is called, a block of stuff is added to the DOM. If the user clicks it repeatedly, the same, identical stuff is added over and over, one after another.
Each block of stuff that is added has some ID suffix that comes from divID, and certain elements in a block have events which affect other elements of the same block. Each block should be self-contained.
However, when the user clicks the button twice, to add two blocks - one with ID suffix 1 and one with ID suffix 2, the events for both blocks affect the child elements for the most recently added block always.
So imagine I have 10 blocks of stuff. All events for all blocks that should be self-contained actually affect the last block, not the block in which they reside.
I know this sort of thing happens in C# when I spool up threads in a loop and the iterating variable plays some role in the thread body:
for (int i = 0; i < 10; i++) {
new Thread(new ThreadStart(delegate() { Console.WriteLine(i); })).Start();
}
Will produce unexpected results - mostly 9's instead of 0 to 9, however:
for (int i = 0; i < 10; i++) {
int j = i;
new Thread(new ThreadStart(delegate() { Console.WriteLine(j); })).Start();
}
Will work fine.
I tried something similar. In my JavaScript code I wrote:
divID++;
localDivID = divID;
and used localDivID instead of divID when setting up the stuff in the DOM. But this had absolutely no effect. I'm still unable to reference the elements with the ID suffix I want.