函数在执行Jquery图像加载之前返回值 [英] Function returns the value before Jquery Image load is executed

查看:78
本文介绍了函数在执行Jquery图像加载之前返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

The above validation function is completing the execution and returning true without the code inside img load function is checked..It means tht even if the image is greater then 400px the validation returns true as the code inside load runs after a long time once the whole Jquery ajax call is sent to api controller.. What I am trying to achieve is that the Validation should not return the value until the code inside the image load is executed.

推荐答案

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

The behaviour is correct as your function will return with 'true' value always. 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. Also if you want to check the width/height of image being loaded, use naturalWidth/naturalHeight as this will give the right values and not the one assigned to the image by css.

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

What you can do is inside image-load function,you can call your function with true/false value as parameter.

这篇关于函数在执行Jquery图像加载之前返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆