问题描述
我正在使用一个网页,使用dojo,并有一个数字(在我的测试用例中,但一般变量)的项目小部件。我调用dojo.addOnLoad(init),在我的init()函数中,我有这些行:
I am working on a web page that uses dojo and has a number (6 in my test case, but variable in general) of project widgets on it. I'm invoking dojo.addOnLoad(init), and in my init() function I have these lines:
dojo.connect(dijit.byId("project" + 0).InputNode, "onChange", function() {makeMatch(0);});
dojo.connect(dijit.byId("project" + 1).InputNode, "onChange", function() {makeMatch(1);});
dojo.connect(dijit.byId("project" + 2).InputNode, "onChange", function() {makeMatch(2);});
dojo.connect(dijit.byId("project" + 3).InputNode, "onChange", function() {makeMatch(3);});
dojo.connect(dijit.byId("project" + 4).InputNode, "onChange", function() {makeMatch(4);});
dojo.connect(dijit.byId("project" + 5).InputNode, "onChange", function() {makeMatch(5);});
并更改我的项目窗口小部件的事件调用makeMatch函数。但是如果我用一个循环替换它们:
and change events for my project widgets properly invoke the makeMatch function. But if I replace them with a loop:
for (var i = 0; i < 6; i++)
dojo.connect(dijit.byId("project" + i).InputNode, "onChange", function() {makeMatch(i);});
相同的makeMatch()函数,同样的init()调用,同样的一切 - 只是滚动我的调用into一个循环 - makeMatch函数从不被调用;对象没有连接。
same makeMatch() function, same init() invocation, same everything else - just rolling my calls up into a loop - the makeMatch function is never called; the objects are not wired.
发生了什么,我如何解决它?我尝试使用dojo.query,但它的行为是与for循环的情况相同。
What's going on, and how do I fix it? I've tried using dojo.query, but its behavior is the same as the for loop case.
推荐答案
问题在处理闭包。请尝试:
this is a common problem when dealing with closures. try this:
for (var i = 0; i < 6; i++) {
(function(i){
dojo.connect(dijit.byId("project" + i).InputNode, "onChange", function() {makeMatch(i);});
}(i));
}
这篇关于为什么我不能在Javascript中滚动循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!