简体   繁体   中英

javascript for-loop repeating last iteration

I am trying to crop-resize n display an image on client-browser using JS. I am able to do so except that my text loop is wrong. You can see in the image below that it is repeating the last iteration. My image loop works fine though. Hint - First filename text is supposed to be black.jpg .

在此处输入图片说明

Am unable to solve the issue after having tried for several hours. Given below is a trimmed version of the code. If needed here is the complete version of the script. Please help, I am still learning.

HTML

<input type="file" id="input" onchange="prevCrop()" multiple> 
<ul id="listWrapper"></ul> 

JAVASCRIPT

function prevCrop() {
    var files = document.querySelector('input[type=file]').files;

    for (var i = 0; i < files.length; i++) {
        var file = files[i]; 
        var fileSize = Math.floor(file.size/1024);
        var info = file.name + " " + fileSize + " KB : iteration number - " + i;

        var reader = new FileReader();
        if (reader != null) {
        reader.onload = GetThumbnail;
        reader.readAsDataURL(file);
        }           
    }


    function GetThumbnail(e) {
        var canvas = document.createElement("canvas");
        var newImage = new Image();
        newImage.src = e.target.result;
        newImage.onload = cropResize; 

        function cropResize() {
            canvas.width = 70;
            canvas.height = 70;
            ### more codes here that handles image   ###

            var dataURL = canvas.toDataURL("image/jpg");
            var thumbList = document.createElement('div');
            thumbList.setAttribute('class', 'tlistClass');  
            var nImg = document.createElement('img'); 
            nImg.src = dataURL;     
            var infoSpan = document.createElement('span');                      
            infoSpan.innerHTML = info;          
            var handle = document.getElementById("listWrapper").appendChild(thumbList);
            handle.appendChild(nImg);
            handle.appendChild(infoSpan);   
        }               
    }

}

This happens because the onload callback function is triggered asynchronously, so after your code has already ended. At that time info has the string that was assigned to it in the last iteration. Only then the onload events are fired, resulting in the different calls of GetThumbnail , which all will see the same value for info .

Instead bind the value of info to the callback function like this:

    reader.onload = GetThumbnail.bind(null, info);

...and define the corresponding parameter for it in the GetThumbnail function:

function GetThumbnail(info, e) {

That way every call of that function will posses of the proper value for info .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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