简体   繁体   English

jQuery变量未更新

[英]jQuery variable not being updated

I am using HTML5 file API to get the width of an image. 我正在使用HTML5文件API来获取图像的宽度。

Its working, and the console.log is outputting the correct amount. 它可以正常工作,并且console.log输出正确的数量。

I need to save the value to the variable fileWidth so I can access it outside the function. 我需要将值保存到变量fileWidth以便可以在函数外部访问它。 I have created an empty variable outside the function, and expected it to be updated with the alue inside the function, but whatever I try fails. 我已经在函数外部创建了一个空变量,并希望通过函数内部的alue更新该变量,但是我尝试执行的任何操作均失败。

Here is my code: 这是我的代码:

var fileWidth;
var reader = new FileReader;
reader.onload = function() {
    var img = new Image;
    img.onload = function() {
        fileWidth = img.width;
        console.log(fileWidth);
    };
    img.src = reader.result;
};

reader.readAsDataURL($('#submission-file')[0].files[0]);

Can anyone see why the variable isn't being updated? 谁能看到为什么不更新变量?

Edited Code: 编辑代码:

var fileWidth;
var reader = new FileReader;
reader.onload = function() {
    var img = new Image;
    img.src = reader.result;
};
reader.onloadend = function() {
    fileWidth = img.width;  
};

reader.readAsDataURL($('#submission-file')[0].files[0]);

console.log(fileWidth);

You're setting fileWidth in an asynchronous callback, this method isn't guaranteed to have executed prior to your accessing the variable. 您正在异步回调中设置fileWidth ,因此不能保证在访问变量之前已执行此方法。

Hint 暗示

Try putting an alert in your callback and an alert right before you access the variable. 尝试在访问变量之前将警报放入回调和警报中。 See which alert is presented first. 查看首先显示哪个警报。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM