1

我的情况是我需要使用javascript检查图像的大小,然后根据其宽度执行一段代码。这是我的代码

        var width, height;
        var img = new Image();
        img.src = "pool.jpg";
        img.onload = function () {
            width = this.width;
            height = this.height;
            console.log(width);
        }
        console.log(width);

        if (width > 0) {
            console.log('in condition check');
            //Some code to be executed
        }
        //Some other code to be executed which cannot be put in the onload portion

问题是该img.onload部分仅在以下代码完成执行后才起作用。有没有办法触发该img.onload功能并以同步方式执行代码。

4

2 回答 2

1

不,您不能让您的代码等到外部任务(通常涉及服务器)完成执行。

必须将代码放在回调中(或从回调中调用的函数中):

   img.onload = function () {
        width = this.width;
        height = this.height;
        console.log(width);
        if (width > 0) {
           console.log('in condition check');
           //Some code to be executed
        }
    }

要构建 JavaScript 应用程序,您必须学会处理基于事件的编程,在这种编程中,您的大部分代码都会根据事件进行操作,无论是用户操作还是异步任务完成。

(技术上有一种方法,但不要使用它)

于 2013-08-16T06:13:47.857 回答
1

您需要等待回调,然后您可以将结果传递给另一个函数:

var width, height;
    var img = new Image();
    img.src = "http://kushsrivastava.files.wordpress.com/2012/11/test.gif";
    img.onload = function () {
        width = this.width;
        height = this.height;
        console.log(width);
        if (width > 0) {
            console.log('in condition check');
            //Some code to be executed
            haveFun(width);
        }
    }
    var haveFun = function(w) {
        console.log('Im having fun with ' + w );
    }

这是一个带有 lil 样本的jsfiddle 。

于 2013-08-16T06:23:04.360 回答