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

これは小さなサンプルを含む jsfiddleです。

于 2013-08-16T06:23:04.360 に答える