jQuery load()函数不设置全局变量

jQuery load() function not setting global variable?

本文关键字:设置 全局变量 函数 load jQuery      更新时间:2023-09-26

不太确定为什么,但我发现这里有人可以教我一点。我希望设置一个基于jQuery加载对象的全局变量。在我的情况下,我是从服务器加载原始图像大小,所以我可以按比例调整它的编程大小。但我困惑的是,为什么我可以警告或控制台日志的高度和宽度,但不能设置一个变量到那些检索值外的回调函数?

HTML:
<img src='someimage.jpg' />
JS/jQuery:
var imgHeight, imgWidth;
$("img").load(function() {
    imgHeight = $(this).height();
    imgWidth = $(this).width();
    console.log(imgWidth + " x " + imgHeight); // this works
});
console.log(imgWidth + " x " + imgHeight); // this does not

这是一个时间问题,什么将是一个更好的解决方案来加载图像,并根据该响应设置一个变量?

这是因为.load函数在加载图像后运行。

console.log正在尝试记录没有值的变量。