Javascript variable not changing inside onload function

杀马特。学长 韩版系。学妹 提交于 2019-12-24 02:43:27

问题


this code always return me '3' in alert.

I select two files together (ones .mp4 format and second ones .zip format)

    function readFile(input) {
        var counter = input.files.length;
        for(x = 0; x<counter; x++){
            if (input.files && input.files[x]) {
                var extension = input.files[x].name.split('.').pop().toLowerCase();
                var reader = new FileReader();

                reader.onload = function (e) {
                    urlss = 1;
                    if(extension == 'mp4'){
                        urlss = 2;
                    }else{
                        urlss = 3;
                    }
                    alert(urlss);
                };
                reader.readAsDataURL(input.files[x]);
            }
        }
    }
<input type="file" id="files" name="files[]" accept=".png, .jpg, .jpeg, .zip, .mp4" onchange="readFile(this);" multiple />

回答1:


That is because of var hoisting

The onload function calling after the for was ended and extension == last file extension

Try replace var with const:

function readFile(input) {
    var counter = input.files.length;
    for(let x = 0; x < counter; x++){
        if (input.files && input.files[x]) {
            const extension = input.files[x].name.split('.').pop().toLowerCase();
            const reader = new FileReader();

            reader.onload = function (e) {
                urlss = 1;
                if(extension == 'mp4'){
                    urlss = 2;
                }else{
                    urlss = 3;
                }
                alert(urlss);
            };
            reader.readAsDataURL(input.files[x]);
        }
    }
}

Update

Please check the Webber's comment below.



来源:https://stackoverflow.com/questions/57638809/javascript-variable-not-changing-inside-onload-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!