[英]no wrap (head) vs onLoad
In this demo , i got different outputs, if i use (no wrap) or (onLoad). 在这个演示中 ,我得到了不同的输出,如果我使用(没有换行)或(onLoad)。
My question is, in html file, to get a correct alert: 1,2,3,4 what alteration is needed in code ? 我的问题是,在html文件中,要获得正确的警报:1,2,3,4代码中需要进行哪些更改? With a simple load of dojo i got always 4 in all alerts: 通过简单的dojo加载,我在所有警报中始终为4:
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js"></script>
<script type="text/javascript">
var slider = [];
for (i = 0; i < 4; i++) {
slider[i] = function () {
alert([i]);
};
dojo.addOnLoad(slider[i]);
}
</script>
You could use a closure : 你可以使用一个闭包 :
var slider = [];
for (i = 1; i < 5; i++) {
slider[i] = (function (i) {
return function () { alert([i]); }
})(i);
dojo.addOnLoad(slider[i]);
}
This will save i
into another functions scope saving the state. 这将把i
保存到另一个保存状态的函数范围。 Without the closure, i
is scoped to the original function. 没有闭包, i
的范围是原始功能。
The value of i is 4 at the end of the loop, which is what your functions will see when they are called. 循环结束时i的值为4,这是您的函数在调用时将看到的值。 Something like this should work: 这样的事情应该有效:
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js"></script>
<script type="text/javascript">
var slider = [];
for (i = 0; i < 4; i++) {
eval("slider[i] = function () { alert([" + i + "]);};");
dojo.addOnLoad(slider[i]);
}
</script>
Edit: well you could also try doing the counting when the functions are called rather than when they're defined. 编辑:你也可以尝试在调用函数时进行计数,而不是在定义函数时进行计数。 eg 例如
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js"></script>
<script type="text/javascript">
var slider = [];
var onLoadCounter = 0;
var onLoadCallback = function() {
alert(onLoadCounter);
onLoadCounter++;
};
for (i = 0; i < 4; i++) {
slider[i] = onLoadCallback;
dojo.addOnLoad(slider[i]);
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.