window.status ="";
function size(file){
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(theFile) {
var image = new Image();
image.src = theFile.target.result;
image.onload = function() {
alert("图片的宽度为"+this.width+",长度为"+this.height);
if(this.width==1072 && this.height==400){
window.status = 'true';
}else{
window.status = 'false';
}
}
}
return window.status;
}
在另一个函数中调用该函数,alert到的返回值内容为空...求解怎么办?
如何定义全局变量,如何给变量再赋值呢?
将里边的那三个 window. 去掉试试看
你没发现你里边的alert比外边的alert 出来的晚吗? 或者说你没有意识到你是在给 window.status 赋值之前试图读值的吗?
return window.status;
这句执行时, 你的 window.status = 'true';
也好 window.status = 'false';
也好都还没有执行呢!
image.onload 是异步,使用回调函数,或者async/await,如果不明白异步建议先查手册了解一下
<body>
<input type="file" onchange="onFileChange(this)">
<script>
/* 回调函数 */
/*
function onFileChange(el) {
let file = el.files[0]
console.log(size(file, function(status){
alert(status)
}))
}
function size(file, callback) {
let status = ''
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (theFile) {
var image = new Image();
image.src = theFile.target.result;
image.onload = function () {
alert("图片的宽度为" + this.width + ",长度为" + this.height);
if (this.width == 1072 && this.height == 400) {
status = 'true';
} else {
status = 'false';
}
callback(status)
}
}
}
*/
/* async/await */
async function onFileChange(el) {
let file = el.files[0]
let status = await size(file)
console.log(status)
}
async function size(file) {
return new Promise(resolve => {
let status = ''
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (theFile) {
var image = new Image();
image.src = theFile.target.result;
image.onload = function () {
alert("图片的宽度为" + this.width + ",长度为" + this.height);
if (this.width == 1072 && this.height == 400) {
status = 'true';
} else {
status = 'false';
}
resolve(status);
}
}
});
}
</script>
</body>