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/