no wrap (head) vs onLoad
In this demo, i got different outputs, if i use (no wrap) or (onLoad).
My question is, in html file, to get a correct alert: 1,2,3,4 what alteration is needed in code ? With a simple load of dojo i got always 4 in all alerts:
<script src="http://ajax.googleapis.com/ajax/lib开发者_如何学编程s/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. Without the closure, i
is scoped to the original function.
The value of i is 4 at the end of the loop, which is what your functions will see when they are called. 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. e.g.
<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>
精彩评论