代码之家  ›  专栏  ›  技术社区  ›  user3861247

无法在image.onload内生成输出

  •  1
  • user3861247  · 技术社区  · 10 年前
    var img = new Image();
    var url = "some url "
    var value = "old value"
    
    img.onError = function() {
      alert('Cannot load image: "'+som+'"');
    };
    
    img.crossOrigin = '';
    img.onload = function() {
      // do something
      value = "New value"
    };
    img.src = som;
    
    alert(value);// pops with "old value"
    

    既然我没有得到我在onload函数中所做的任何更改?我在onload函数中存储的结果不能全局使用?

    3 回复  |  直到 10 年前
        1
  •  0
  •   Spokey    10 年前

    之后的代码 onload 不会在执行之前等待它完成。

    var value = 'old value';
    
    img.onload = function () { // image did not load yet, still waiting
        // do something
        value = "New value"
    };
    
    alert(value); // doesn't care if onload is done or not
    

    自从 超载 alert() 显示值未更改。你需要回调或类似的东西

    var value = 'old value';
    
    img.onload = function () {
        // do something
        value = "New value"
    
        imageLoaded();
    };
    
    function imageLoaded() { // or just give the value as parameter
        alert(value);
    }
    
        2
  •  0
  •   Ferdi265    10 年前

    问题是,内部的函数 img.onload 在alert(value);`之后执行。

    时间线:

    • value = "old value";
    • img.onload设置为函数(尚未执行)
    • alert(value);
    • 图像已加载
    • value = "new value";

    如果您键入 value 在加载图像后,它应该是“新值”。

        3
  •  0
  •   Brandon Gano    10 年前

    根据您的代码 alert 将显示“旧值”,因为它在 onload 回调。由于异步代码的魔力,执行顺序概述如下:

    // 1: Declare variables
    var img = new Image();
    var url = 'some url';
    var value = 'old value';
    
    // 2: Assign callback
    img.onload = function () {
      // 4: Update value
      value = 'new value';
    };
    
    // 3: Alert value
    alert(value);
    

    如果您不相信我,请在警报中添加延迟:

    // THIS IS BAD CODE. It's just to prove that your callback is executing.
    setTimeout(function () {
      alert(value);
    }, 10000);
    

    只要您的图像加载时间不超过10秒,这将为您提供预期的输出。