Javascript 检查图像是否存在,变量值不变
此代码检查是否存在图像 在onload函数中,我想用一个布尔值更改变量“control”Javascript 检查图像是否存在,变量值不变,javascript,image,variables,onload,Javascript,Image,Variables,Onload,此代码检查是否存在图像 在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 = fu
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)在调用image
的onload
或onerror
函数之前调用code>
控件
变量会更改,但在更改前调用日志
。您可以将代码修改为类似以下内容,以实现所需:
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);
}
您也可以在此处进行检查。函数image.onload仅在加载图像后执行,执行可能需要500-1200ms
console.log(控制)代码>在加载图像之前执行,这就是为什么总是显示为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);
}