i have come code below. problem on change every element alerts last iteration index. example if there 24 items on elements array every single element on change alert "changed row 23" . kind of see why happening cant find away around every element onchange alert index instead of last. appreciated.
for (var = 1; < elements.length; i++) { elements[i].onchange = (ev: event) => alert("changed row " + i); userstable.appendchild(elements[i]); }
when events executed, loop have completed. @ point i
equal whatever when loop ended—elements.length - 1
(which why it's equal 23 you).
you can fix using brocco's solution, since want know way of doing without changing loop, need pass in value of i
when setting change function. can achieved using iife:
for (var = 1; < elements.length; i++) { (function (i) { userstable.appendchild(elements[i]); elements[i].onchange = (ev: event) => alert("changed row " + i); })(i); }
which longer way of expressing .foreach
function you.
alternatively, use .bind
:
elements[i].onchange = function(i: number, ev: event) { alert("changed row " + i) }.bind(this, i);
Comments
Post a Comment