Jquery从嵌套函数返回

Jquery return from nested function

本文关键字:返回 函数 嵌套 Jquery      更新时间:2023-09-26

这是我的代码

 <input type="file" id="choose" multiple="multiple" />
<br>
<div id="uploadPreview"></div>

function readImage(file) {
    var reader = new FileReader();
    var image  = new Image();
    reader.readAsDataURL(file);  
    reader.onload = function(_file) {
        image.src    = _file.target.result;              // url.createObjectURL(file);
        image.onload = function() {
            var w = this.width,
                h = this.height,
                t = file.type,                           // ext only: // file.type.split('/')[1],
                n = file.name;
             if (h < 400 || w < 400) {
                 alert('in');
                    return true;
                }
        };
    };
}
$("#choose").change(function (e) {
    var F = this.files;
    alert( readImage( F[0]) );
});

当我上传低图像时,它总是返回未定义的

Fiddle

您可以获得类似的返回值

function readImage(file, callback) {
    var reader = new FileReader();
    var image  = new Image();
    reader.readAsDataURL(file);  
    reader.onload = function(_file) {
        image.src    = _file.target.result;              // url.createObjectURL(file);
        image.onload = function() {
            var w = this.width,
                h = this.height,
                t = file.type,                           // ext only: // file.type.split('/')[1],
                n = file.name;
             if (h < 400 || w < 400) {
                 alert('in');
                    callback(true);
                }
        };
    };
}

$("#choose").change(function (e) {
    var F = this.files;
    readImage( F[0], function(value){
        alert( value );
    });
});