函数 returns 执行 Jquery 图像加载之前的值

Function returns the value before Jquery Image load is executed

if (DataService.Validation(file)) {
    //angularjs call to api controller
};    

//DataService
Validation: function (file) {
    var Url =   URL.createObjectURL(file);
    var img = new Image();

    $(img).load(function () {
        var imgwidth = this.width;
        var imgheight = this.height;
        if (imgheight  > 400) {
            viewModel.ErrorMessage = 'The Image height cannot be more then 400 px.';
            return false;
        }
    });

    img.src = Url;

    if (file == null) {
        viewModel.ErrorMessage = 'Please select a file to upload.';
        return false;
    }

    if (viewModel.Name == null) {
        viewModel.ErrorMessage = 'Name is a required field.';
        return false;
    }

    return true;
}

上面的验证函数正在完成执行并且 return 在没有检查 img 加载函数内的代码的情况下为真..这意味着即使图像大于 400px 验证 return这是真的,因为一旦整个 Jquery ajax 调用被发送到 api 控制器,load 中的代码会在很长一段时间后运行。 我想要实现的是,在执行图像加载中的代码之前,验证不应该 return 值。

该行为是正确的,因为您的函数将 return 始终具有 'true' 值。 IMG 加载函数只会在您的图像被浏览器完全加载后执行,并且由于它是异步的,您的函数不会等待它执行。 此外,如果您想检查正在加载的图像的 width/height,请使用 naturalWidth/naturalHeight,因为这将给出正确的值,而不是 css 分配给图像的值。

你可以做的是在图像加载函数中,你可以用 true/false 值作为参数调用你的函数。

我在检查图像尺寸时遇到了同样的问题,因为图像加载是异步的。也正如@Abhinandan所说 "IMG load function will execute only after your image is completely loaded by the browser and since its asynchronous your function will not wait for it to execute"

我使用了以下方法。希望对你有帮助。

像下面这样更改文件时在图像标签中设置一个额外的属性

$('input[type=file]').on('change',function(){
    element = $(this);
    var files = this.files;
    var _URL = window.URL || window.webkitURL;
    var image, file;
    image = new Image();
    image.src = _URL.createObjectURL(files[0]);
        image.onload = function() {
            element.attr('uploadWidth',this.width);
            element.attr('uploadHeigth',this.width);
        }
    });

现在您可以将函数修改为以下

$.validator.addMethod('checkDim', function (value, element, param) {     
    var image = new Image();
    var file = element.files[0];
    var _URL = window.URL || window.webkitURL;
    image.src = _URL.createObjectURL(file);
        if(element.uploadWidth== param[0] element.uploadHeigth== param[1]){ 
            return true;
        }
        else{            
            return false;
        }

}, 'Image dimension must be as specified');

对我有用