简体   繁体   English

jquery.each-将计数器传递给子.onload函数

[英]jquery.each - passing the counter to child .onload function

somehow my counter variable is not passed to the child function. 不知何故我的计数器变量没有传递给子函数。 i'm guessing it's because of some asyncronous behavior but actually i have no clue. 我猜这是由于一些异步行为,但实际上我不知道。 please help. 请帮忙。

$(document).ready(function() {
    var imgArray = new Array();
    $("canvas").each(function(i) {
        imgArray[i] = new Image();
    });
    $.each(imgArray, function(i) {
        alert(i);
        //correct output

        this.onload = function() {
            alert(i);
            //"undefined"

            var width = this.width,
                height = this.height;
            var context = $("canvas")[i].getContext("2d");
            //here's the error

            /* more code */
        };
        this.src = "PATH";      
    });
});

so how can i pass the value for the right canvas? 那么如何传递正确画布的值?
thanks for any help! 谢谢你的帮助!

The problem you're experiencing is due to the nature of how JavaScript supports closures. 您遇到的问题是由于JavaScript支持闭包的性质所致。 That is not to say that the problem is a bug; 这并不是说问题是一个错误,而是一个错误。 it's behaving exactly as it's should. 它的表现完全正确。 The onload method is being executed after i has already been iterated all the way through and becomes undefined . i一直迭代到undefined之后,将执行onload方法。 A viable solution is to use closures to your advantage and wrap the function creation in a call, such as this.onload = (function(index) { /* ... */ })(i); 一个可行的解决方案是利用闭包来发挥您的优势,并将函数创建包装在调用中,例如this.onload = (function(index) { /* ... */ })(i);

This guarantees that the value is stored as expected in an variable internally accessible to the onload methods you're creating. 这样可以确保将值按预期存储在所创建的onload方法可内部访问的变量中。

correct this part of yours to this part. 将此部分更正为这一部分。

   this.onload = (function(a) {
            alert(a);
            //"undefined"

            var width = this.width,
                height = this.height;
            var context = $("canvas")[a].getContext("2d");
            //here's the error

            /* more code */
        })(i);

I created a closure so that the i value will be catched as it was on the loop iteration. 我创建了一个闭包,以便可以像在循环迭代中那样捕获i值。

I will supply a simple example : 我将提供一个简单的示例:

var i=0;

i++;
alert(i) //1

i++;
alert(i) //2


alert(i) //2 !!!

this is what actually happens in you code. 这就是代码中实际发生的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM