检查图片是否存在,变量值不变

Check if image exist, The value of variable not change

此代码检查图像是否存在。

在函数 onload 中,我想用布尔值更改变量 'control'。

var control = 'a.jpg';
var image_name = control;
var image = new Image();

image.onload = function() {
    control = true; // Why this change does not happen outside of this function?
};
image.onerror = function() {
    control = false; // Why this change does not happen outside of this function?
};
image.src = image_name;

console.log(control); // The value is not changed in a boolean

但是在函数之外,变量并没有改变。为什么?

谢谢

这是因为 console.log(control); 在调用 imageonloadonerror 函数之前被调用。

control 变量发生变化,但您在它发生变化之前调用了 log。您可以将代码修改为类似这样的内容以实现您想要的:

var control = 'a.jpg';
var image_name = control;
var image = new Image();

image.onload = function() {
    control = true;
    after();
};
image.onerror = function() {        
    control = false;
    after();
};
image.src = image_name;

function after(){
    alert(control);
    console.log(control);
}

你也可以在这个JSFiddle里查看。

函数image.onload只在加载图片后执行,可能需要500-1200ms执行,

console.log(control); 在加载图像之前执行这就是为什么总是显示为 false

尝试在几秒延迟后打印控制值

var control = 'a.jpg';
var image_name = control;
var image = new Image();

image.onload = function() {
    control = true; // Why this change does not happen outside of this function?
};
image.onerror = function() {
    control = false; // Why this change does not happen outside of this function?
};
image.src = image_name;
setTimeout(function(){ 
console.log(control); // its work
},2000);

像这样更改代码结构

var control = 'a.jpg';
var image_name = control;
var image = new Image();

image.onload = function() {
    control = true; 
    nextProcess();
};
image.onerror = function() {
    control = false; 
    nextProcess();
};
image.src = image_name;
function nextProcess(){
  console.log(control);
}