【发布时间】:2021-08-21 12:09:24
【问题描述】:
我正在调用一个 JavaScript 函数,我想在上传之前验证图像的高度和宽度。我返回 false 值,但在源函数中,当它是控制台日志时,它会给出 undefined。
为了更好地理解,请检查代码。代码运行良好,但我想从 JavaScript 函数中获取 true 和 false。
$(document).on('change', '#userfile', function() {
var result = ValidateAuthorImage(event, $(this));
console.log(result);
});
function ValidateAuthorImage(event, obj) {
var files = event.target.files;
var valid = true;
var height = 0;
var width = 0;
var _URL = window.URL || window.webkitURL;
for (var i = 0; i < files.length; i++) {
var img = new Image();
img.onload = function() {
height = img.height;
width = img.width;
//alert(width + " " + height);
if (width < 700 || height < 500) {
$("#msg_upload").html('<span style="color:red;">Please uplaod image with at least width = 700 and height = 500 </span>');
obj.value = "";
return false;
} else {
$("#msg_upload").html('');
}
}
img.src = _URL.createObjectURL(files[i]);
}
}
【问题讨论】:
-
请详细一点
-
你的函数只返回
false。 然而更大的问题是onload实际上是异步的,所以你不能从onload处理函数返回任何东西到外部ValidateAuthorImage()范围。您需要更改用于图像尺寸验证的模式,因为您尝试做的事情是不可能的。我建议验证图像并在未通过检查的图像旁边显示消息/错误。
标签: javascript jquery image height width