开发者

no wrap (head) vs onLoad

开发者 https://www.devze.com 2023-04-12 18:32 出处:网络
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 g

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>
0

精彩评论

暂无评论...
验证码 换一张
取 消