javascript - 无法在 image.onload 内生成输出

标签 javascript jquery function onload

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 函数中的结果不能全局使用?

最佳答案

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

由于 onload 在显示 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);
}

关于javascript - 无法在 image.onload 内生成输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24927642/

相关文章:

javascript - 为什么我的 Angular JS 应用程序无法运行?

algorithm - 查找数组中的偶数

c++ - 通过引用将对象传递给函数不会更改此对象

javascript - 使用 Javascript 数组对数字进行阶乘

javascript - 在 javascript 中实现 OOP 的更好方法

javascript - 使用 Firebase 5.6.0 注销

javascript - JQuery - 语法错误 : reserved word "this" can't be assigned

jquery - Jscrollpane 移动内容

javascript - jQuery 中的 "Converting"具有多个音轨的音频播放器

javascript - 使用多个分隔符拆分字符串