Vanilla Javascript: counter variable of for loop undefined when used in function -
this sudoko generator i'm programming in vanilla javascript:
nicer looking full screen jsfiddle
if click on 1 of fields, popup shown 3x3 fields 1 9. if click on 1 of fields of popup f. ex. 5, should change parent field 5. problem changes parent field undefined.
here relevant code generate popup:
// create popup function createpopup(position) { var popup = document.createelement('dialog'); popup.classname = 'popup'; popup.id = 'window_' + position; var dialogblock = popup.appendchild(document.createelement('div')); dialogblock.classname = 'popupblock'; (var z = 1; z <= 9; z++) { var div = dialogblock.appendchild(document.createelement('div')); div.classname = 'popupcell'; div.id = position + 'z' + z; div.appendchild(document.createtextnode(z)); div.onclick = function (e, z) { document.getelementbyid(position).innerhtml = z; e.stoppropagation(); popup.close(); }; } return popup; } the problem seems z in scope when passing div.onclick. how can pass z function?
problem #1
the event handler function assigned globaleventhandlers.onclick passed 1 argument when called.
div.onclick = function (e, z) there no second argument, rid of , z here.
problem #2
because onclick function not executed until element receives click event, need wrap body of for-loop in invoked function expression1,2 in order create new lexical scope each iteration of loop.
this makes z in context of event handler reference value of z in current iteration of loop instead value of z @ at last iteration of loop.
for (var z = 1; z <= 9; z++) (function(z){ var div = dialogblock.appendchild(document.createelement('div')); div.classname = 'popupcell'; div.id = position + 'z' + z; div.appendchild(document.createtextnode(z)); div.onclick = function (e) { console.log(e, z); document.getelementbyid(position).innerhtml = z; e.stoppropagation(); popup.close(); }; })(z);
Comments
Post a Comment