[英]Vanilla Javascript: counter variable of for loop undefined when used in function
This is a Sudoko generator I'm programming in vanilla javascript: 这是我在香草javascript中编程的Sudoko生成器:
Nicer looking full screen JSFiddle 看起来更好的全屏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. 如果单击其中一个字段,将显示一个弹出窗口,其中包含从1到9的3x3字段。如果您单击弹出窗口f的其中一个字段。 ex. 恩。 5
, it should change the parent field to 5
. 5
,应将父字段更改为5
。 The problem is that it changes the parent field to undefined
. 问题在于它将父字段更改为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
. 问题似乎是z
传递给div.onclick
时在另一个作用div.onclick
。 How can I pass z
to another function? 如何将z
传递给另一个函数?
The event handler function assigned to GlobalEventHandlers.onclick
will only be passed one argument when called. 分配给GlobalEventHandlers.onclick
的事件处理函数仅在调用时传递一个参数。
div.onclick = function (e, z)
There is no second argument, get rid of , z
here. 没有第二个参数,在这里摆脱, z
。
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. 因为直到元件接收click事件的onclick功能不会被执行,你需要用身体的for循环中的立即调用的函数表达式1 , 2 ,以创建循环的每个迭代一个新的词汇范围。
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. 这使得z
在事件处理的情况下参考价值z
在循环而不是价值的当前迭代z
在在循环的最后一次迭代。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.