这是我所拥有的:
var test = '';
var img = new Image();
img.src = 'https://blahblah';
img.onload = function () {
test = 'Sam';
}
当我console.log(test)
时,它什么也没显示。如何在onload
内部为test
赋值?
看到这个jsFiddle: https://jsfiddle.net/y7Lnp6q1/1/
这取决于您在哪里进行控制台.log。请参阅以下代码中的注释:
var test = "";
var img = new Image();
img.src = 'https://developers.google.com/search/docs/data-types/images/recipes01.png';
img.onload = function () {
test = "Sam";
console.log("test = " + test); // Will output "test = Sam"
}
console.log("test = " + test); // Will output "test = ", because onload is not yet triggered by this time.