gpt4 book ai didi

javascript - 处理异步加载的函数中的无限循环

转载 作者:行者123 更新时间:2023-11-28 18:54:36 25 4
gpt4 key购买 nike

这是一个 jquery 脚本,在用户选择要上传的文件后触发(代码有点乱,不利于调试)。1. 用户选择 jpeg 图像文件 (f) 后,将加载图像并将其宽度和高度与允许的最大值进行比较。2. 如果图像太大,则调用resize缩小尺寸。3. 由于图像onload是异步的,因此调用回调函数afterloading(image):

$(function(){
$('#uploaded_file_file_for_upload').change(function(){
var _URL = window.URL || window.webkitURL;
var img;
var max_width = 0;
var max_height = 0;
var max_size_mb;
var f = $(this)[0].files[0];
if (f != null) {
max_width = $('#max_width').val();
max_height = $('#max_height').val();
max_size_mb = $('#max_size_mb').val();
alert(max_width +', ' + max_height);
$('#file_name').val(f.name);
alert(f.name);
$('#file_size').val(f.size/1024);
$('#file_type').val(f.type); //image/jpeg
$('#file_extension').val(f.name.split('.').pop().toLowerCase());
alert(f.type);
alert(f.name.split('.').pop().toLowerCase());
if (f.type == 'image/jpeg') {
img = new Image();
img.onload = function () {
afterloading(this);
return false;
};
img.src = _URL.createObjectURL(f);
};
};


function afterloading(image) {
var w = image.width, h = image.height;
alert('hi-max' + max_width + ' -- ' + max_height);
alert('hi' + w + ' xx ' + h);
if (w > max_width || h > max_height) { img.src = _URL.createObjectURL(f);
if (w > max_width){
h = Math.ceil(h * max_width / w);
w = max_width;
} else if (h > max_height) {
w = Math.ceil(w * max_height / h);
h = max_height;
};
alert('before resize, ' + w + ' ?? ' + h );
resize(image, w, h);
$('#remove').val('true');
return false;
};
};

function resize(image, width, height) {
alert('resize');
var mainCanvas = document.createElement("canvas");
mainCanvas.width = width;
mainCanvas.height = height;
var ctx = mainCanvas.getContext("2d");
ctx.drawImage(image, 0, 0, width, height);
$('#uploaded_file_hidden_file').val(mainCanvas.toDataURL("image/jpeg"));
$('#file_size').val(image.size/1024);
alert($('#file_size').val());
alert("++" + image.size);
return false;
};

return false;

});
});

问题在于执行afterloading(image)会导致无限循环。什么可能导致无限循环?

更新:

afterloading 中注释掉 resize(image, w,h) 后,也会出现同样的无限循环。所以问题出在 afterloading 本身。

最佳答案

我只是在这里猜测,因为你没有向 jsfiddle 提供上面的代码,但是这里加载的 img 是什么,什么时候加载的?

img = new Image();
img.onload = function () {
afterloading(this);
return false;
};

afterloading 需要一个 image 对象,它似乎位于 f 中。尝试将 f 传递给 afterloading 看看它是否有效,因为上面的内容应该做你想做的事情。

编辑:

此外,afterloading 中的 this 看起来是您上面刚刚创建的 img 对象的范围,该对象是空的。

关于javascript - 处理异步加载的函数中的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33864528/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com