无法为image.onload()中的范围变量赋值

时间:2016-05-20 18:12:45

标签: jquery image scope onload

这就是我所拥有的:

samplepool <- rep(names(q), q)  

当我var test = ''; var img = new Image(); img.src = 'https://blahblah'; img.onload = function () { test = 'Sam'; } 时,它什么也没有显示。如何为console.log(test)内的test分配值?

1 个答案:

答案 0 :(得分:0)

请参阅此jsFiddle:https://jsfiddle.net/y7Lnp6q1/1/

这取决于你在哪里做console.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.