2017-02-27 46 views
0

该代码检查是否存在图像。检查图像是否存在,变量值不变

函数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 

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

感谢

回答

0

功能image.onload只加载图像后执行的,它可能需要500-1200ms执行,

console.log(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; 
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); 
} 
0

这是因为被称为的imageonloadonerror功能之前,先console.log(control);被调用。

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