Javascript only sets attribute for last item in ar

2019-01-12 12:44发布

问题:

I have an array of ~50 items and in javascript it goes through this array to check a condition and if the condition is met it setsattribute for checkboxes on the be checked. It goes through nicely but only changes the very final item in the array every time. Here is a section of the code.

for (i = 0; i < urlArray.length; i++) {
    var newImg = new Image();
    var coName = companyArray[i];
    newImg.onload = function(){
        if (condition is met){
            nStar++;

                    document.getElementById(coName).setAttribute("checked", "checked");
                    document.getElementById(coName).checked = true;
        } else {
            nStar++;

                    document.getElementById(coName).setAttribute("checked", "checked");
                    document.getElementById(coName).checked = true;
                    document.getElementById(coName).setAttribute("disabled", "disabled");
                    document.getElementById(coName).disabled = true;        
        }

    };

So as you can see if the condition is met or not it will still change the attributes but the error I have been receiving is that it only changes the final item in the array. Any ideas?

回答1:

This is a classic issue with an asynchronous callback in Javascript. The onload handler will be called some time later, long after the for loop has finished, thus the index in the for loop is pegged at the end where it ended up and the local variables newImg and coName will only have their last values in the loop.

Any variables that you wish to use inside the onload handler will have to passed into the actual function closure so that they are uniquely available for each different onload handler. There are several ways to do that.

This way uses a function closure to capture the passed in value and make it available to the onload function handler:

for (i = 0; i < urlArray.length; i++) {
    var newImg = new Image();
    var coName = companyArray[i];
    newImg.onload = (function (coName) {
        return function(){
            if (condition is met){
                nStar++;
                document.getElementById(coName).setAttribute("checked", "checked");
                document.getElementById(coName).checked = true;
            } else {
                nStar++;
                document.getElementById(coName).setAttribute("checked", "checked");
                document.getElementById(coName).checked = true;
                document.getElementById(coName).setAttribute("disabled", "disabled");
                document.getElementById(coName).disabled = true;        
            }
        };
    }) (coName);
}

In Javascript-speak, what this method does is assign to the onload attribute the return value from executing an anonymous function call. That anonymous function call passed the coName parameter into it. That function returns another anonymous function which is what gets assigned as the onload handler. But, because of the way function closures work in javascript, the value of coName is captured in the function closure and is kept accessible to the onload handler for the duration of the function closure. One can think of it a little like an instance of a function with state around it (values of local variables) that is uniquely capture each time it's set up. In this case, it captures the value of the coName variable and puts it into the closure where it becomes unique and won't be effected by later changes to the outer coName variable that's in the for loop.

Another way to do it is to put the parameter on the actual object so you can retrieve it from there:

for (i = 0; i < urlArray.length; i++) {
    var newImg = new Image();
    newImg.setAttribute("coName". companyArray[i]);
    newImg.onload = function() {
        var coName = this.getAttribute("coName");
        if (condition is met){
            nStar++;
            document.getElementById(coName).setAttribute("checked", "checked");
            document.getElementById(coName).checked = true;
        } else {
            nStar++;
            document.getElementById(coName).setAttribute("checked", "checked");
            document.getElementById(coName).checked = true;
            document.getElementById(coName).setAttribute("disabled", "disabled");
            document.getElementById(coName).disabled = true;        
        }

    };
}


回答2:

The problem is that the variable coName will always be the last array value by the time any of the function are executed. You can do something like this:

for (i = 0; i < urlArray.length; i++) {
    var newImg = new Image();
    var coName = companyArray[i];
    newImg.onload = (function(name){
        return function(){
            if (true) {
                nStar++;
                document.getElementById(name).setAttribute("checked", "checked");
                document.getElementById(name).checked = true;
            } else {
                nStar++;

                document.getElementById(name).setAttribute("checked", "checked");
                document.getElementById(name).checked = true;
                document.getElementById(name).setAttribute("disabled", "disabled");
                document.getElementById(name).disabled = true;
            }
        }
    })(coName);
}