简体   繁体   中英

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

This is a Sudoko generator I'm programming in vanilla javascript:

JSFiddle

Nicer looking full screen JSFiddle

If you click on one of the fields, a popup will be shown with 3x3 fields from 1 to 9. If you click on one of the fields of the popup f. ex. 5 , it should change the parent field to 5 . The problem is that it changes the parent field to undefined .

Here is the relevant code where I generate my 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';

        for (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 to be that z is in another scope when passing it to div.onclick . How can I pass z to another function?

Problem #1

The event handler function assigned to GlobalEventHandlers.onclick will only be passed one argument when called.

div.onclick = function (e, z)

There is no second argument, get rid of , z here.

Problem #2

Because the onclick function will not be executed until that element receives a click event, you need to wrap the body of your for-loop in an immediately invoked function expression 1 , 2 in order to create a new lexical scope for each iteration of the loop.

This makes z in the context of your event handler reference the value of z in the current iteration of the loop instead the value of z at the at the last iteration of the 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM