简体   繁体   English

为jQuery函数调用设置布尔返回值

[英]Setting a boolean return value to a jQuery function call

I have a function here that checks if a picture has the dimensions of 100 by 100 pixels and if so returns true 我这里有一个函数,用于检查图片是否具有100 x 100像素的尺寸,如果是,则返回true

function checkDims(url) {
    var valid = $("<img/>").attr("src", url).load(function() {
        s = { w: this.width, h: this.height };
        if (s.w == 100 && s.h == 100) {
            return true;
        }
        else {
            return false;
        }
    });
    return valid;
}

I want to set a variable called valid that checks by using a .load function to get the image size of a remote URL and I want it to return true or false accordingly. 我想设置一个称为有效的变量,该变量使用.load函数进行检查以获取远程URL的图像大小,并且我希望它相应地返回true或false。 I know I'm setting it to a jQuery object but I want to get the results from the inner function. 我知道我将其设置为jQuery对象,但我想从内部函数中获取结果。

I tried doing: 我试着做:

function checkDims(url) {
    var valid;
    $("<img/>").attr("src", url).load(function() {
        s = { w: this.width, h: this.height };
        if (s.w == 100 && s.h == 100) {
            valid = true;
        }
        else {
            valid = false;
        }
    });
    return valid;
}

But it gave me undefined as a value for valid when I called the checkDims function 但是当我调用checkDims函数时,它给我未定义为有效的值

so if I called 所以如果我打电话

var s = checkDims(a_url) var s = checkDims(a_url)

. It would return 它会回来

undefined 未定义

You need to break up your logic into two steps since this is an asynchronous call. 您需要将逻辑分为两个步骤,因为这是一个异步调用。

function checkDims(url, callback) {
    $("<img/>").attr("src", url).load(function() {
        callback (this.width == 100 && this.height == 100);   
    }).on("error") { callback(false); });
}

function nextStep(isValid) {
    alert("The image is " + ((isValid) ? "" : "not ") + "valid"
}

checkDims("foo.gif", nextStep);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM