Vanilla Javascript: counter variable of for loop undefined when used in function -


this sudoko generator i'm programming in vanilla javascript:

jsfiddle

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.

jsfiddle

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

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -