我有一个用于上传图像的输入文件。但是,我必须在上传之前验证其大小。下面是我尝试过的代码。
我有一个父函数,它调用方法 ValidateImageSize( ):
$('input:file').change(function (e) {
if (ValidateImageSize(this))
// do something
else
alert("wrong size");
});
方法如下:
var ValidateImageSize = function (input) {
var reader = new FileReader();
reader.onload = function (e) {
var img = new Image();
img.onload = function (e) {
return this.height == 40 && this.width == 40 ? true : false;
}
img.src = e.target.result;
}
reader.readAsDataURL(input.files[0]);
};
方法 ValidateImageSize()
始终向其父级返回“undefined
”,因为它尚未执行 onload 函数。
我需要的输出是真/假。也许我的代码本身的结构是不正确的。
我该如何解决这个问题?
最佳答案
使用回调
,如下所示:
var validation_callback = function(isValid) {
if (isValid) {
// do something
} else {
alert("wrong size");
}
};
$('input:file').change(function(e) {
ValidateImageSize(this, validation_callback);
});
var ValidateImageSize = function (input, callback) {
var reader = new FileReader();
reader.onload = function (e) {
var img = new Image();
img.onload = function (e) {
var isValid = this.height == 40 && this.width == 40 ? true : false;
callback(isValid);
};
img.src = e.target.result;
};
reader.readAsDataURL(input.files[0]);
};
关于javascript - 仅当调用 return 时才退出函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23949631/