在将所有图像存储在本地存储中之后如何调用函数

时间:2017-01-09 16:03:11

标签: javascript jquery asynchronous

我的代码是将输入中的图像存储在本地存储中。我想使用window.location.href =" / case-form&#34 ;;更改我的页面。存储所有图像时(完成onInputChange函数中的所有操作后)。

$(document).ready(function() {        
    $(document).on('change', '#images-upload-input', function() {
        onInputChange();
    });
});

function onInputChange() {
    clearStockedImages();
    //get files from #images-upload-input input
    var files = $("#images-upload-input", 'body')[0].files;
    for (var i = 0; i < files.length; i++) {
        if (files && files[i]) {
            $('body').append("<img src='' id='photo-upload-" + i + "'/>");
            var reader = new FileReader();
            reader.onload = (function(i) {
                return function(e) {
                    document.getElementById('photo-upload-' + i).src = e.target.result;
                    storeBase64Image(document.getElementById('photo-upload-' + i), function(result) {
                        localStorage.setItem('imgData-' + i, result);
                    });
                };
            })(i);
            reader.readAsDataURL(files[i]);
        }
    }   
}


//Delete all images previously stocked in local storage
function clearStockedImages() {
    Object.keys(localStorage)
            .forEach(function(key) {
                if (/^(?:imgData-)/.test(key)) {
                    localStorage.removeItem(key);
                }
            });
}
function getBase64Image(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);
    var dataURL = canvas.toDataURL("image/png");
    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
function storeBase64Image(img, store) {
    if (img.complete) {
        store(getBase64Image(img));
    } else {
        img.onload = function() {
            store(getBase64Image(img));
        };
    }
}

1 个答案:

答案 0 :(得分:1)

回调怎么样?

$(document).ready(function() {        

    $(document).on('change', '#images-upload-input', function() {

        onInputChange(function(){

            window.location.href = window.location.href + "/case-form";

        });

    });

 });

function onInputChange(callback) {

    ....
    for (var i = 0; i < files.length; i++) {
        ....
    } 

    ....

    if(callback){
        callback();
    }


}