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;
}


上面的验证函数完成了执行并返回了true,而无需检查img load函数中的代码。这意味着即使图像大于400px,验证也会返回true,因为加载后的代码将在很长一段时间后运行jQuery ajax调用发送到api控制器。
我要达到的目的是,在执行图像加载内的代码之前,验证不应该返回该值。

最佳答案

该行为是正确的,因为您的函数将始终返回“ true”值。
IMG加载功能仅在浏览器完全加载了图像之后才执行,并且由于它是异步的,因此您的函数将不等待其执行。
另外,如果要检查要加载的图像的宽度/高度,请使用naturalWidth / naturalHeight,因为这将提供正确的值,而不是css分配给图像的值。

您可以在图像加载函数内部进行操作,可以使用true / false值作为参数来调用函数。

关于javascript - 函数在执行Jquery图像加载之前返回值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29746285/

10-12 13:02
查看更多