0

I'm having an issue wherein the loop, a value dependant on the i-value of the loop modifies the values of the previously looped values. So for example a variable given the value i then resets to a higher value i when it loops around a second time when really I'm trying to create multiple i-value items. So if I loop it ten times I should have 10 items with different IDs. But instead, all 10 items end up with the same ID which ends up becoming an issue when I call that ID in a function.

for (i = 0, i < array.length, i++)
{
    var id = array[i][0];
    var tag = document.createElement('h5');
    tag.id = i;
    tag.onclick = function(){comment(id, this.id)}
}

function comment(id, i)
{
    console.log(id);
    console.log(i);
}

So this.id works completely fine, but the first value 'id' inputted in the comment function results in the last var id result to come up. How do I have it so that I can use all the ids? Sorry for the confusing introduction, there's 2 types of id the id given to the element and the id that comes in from the server to keep track of different posts and I'm having issues with the latter as I found a workaround solution of using this.id to solve one of the issues.

Thanks!

Yun Jae Jung
  • 139
  • 1
  • 8

0 Answers0