我正在尝试从通过 ajax 函数返回的路径列表(长 10 项)中读取图像,调整每个图像的大小,然后在页面上一个接一个地显示。但是,下面的代码仅显示第一个图像(调整大小),而不显示其他图像。我相当确定调整大小是有效的,因为打印的尺寸看起来是正确的。下面是我的 JavaScript 代码:
// Helper function
function scaleSize(maxW, maxH, currW, currH){
var ratio = currH / currW;
if(currW >= maxW && ratio <= 1) {
currW = maxW;
currH = currW * ratio;
} else if(currH >= maxH) {
currH = maxH;
currW = currH / ratio;
}
return [currW, currH];
}
function get_similar_images(image_name) {
console.log(image_name)
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/get_similar",
dataType: "json",
async: true,
data: JSON.stringify({name: image_name}),
success: function(data) {
console.log(data);
image_list = data['images']
category = data['category']
for (var i=0; i<image_list.length; i++) {
var img = document.createElement("img");
img.src = "static/products/"+category+"/"+image_list[i];
var actualH;
var actualW;
var newH;
var newW;
img.onload = function(){
actualW = this.width;
actualH = this.height;
console.log(actualW, actualH)
var newSize = scaleSize(300, 300, actualW, actualH);
console.log(newSize)
img.width = newSize[0];
img.height = newSize[1];
document.getElementById('imageDiv').appendChild(img)
};
}
},
error: function(xhr, status, error) {
// console.log(xhr.responseText);
}
})
}
最佳答案
如果我们像这样简化您的 for
循环:
var img = document.createElement("img");
img.src = image_list[0];
img.onload = function() {
console.log(img);
};
var img = document.createElement("img");
img.src = image_list[1];
img.onload = function() {
console.log(img);
};
你会明白你的错误从何而来。 onload
是一个事件,这意味着它与您的代码异步运行。在触发第一个 load
事件之前,您将使用新的图像元素(和新的 href
属性)更新 img
值。因此,onload
事件实际上是在 img
变量最后一次更新之后调用的,这实际上是在到达 for
的最后一个循环时发生的。
为什么?
因为 for
循环不会为变量 img
创建新的作用域,所以每次触摸 img
var 时,即使如果您将 var
放在前面,则原始 img
会更新。
然后您应该使用函数,因为函数实际上为在其中声明的变量 (var myVar
) 创建了一个新作用域:
function injectAndResize(imageUrl) {
var img = document.createElement("img");
img.src = imageUrl;
var actualH;
var actualW;
var newH;
var newW;
img.onload = function() {
actualW = this.width;
actualH = this.height;
var newSize = scaleSize(300, 300, actualW, actualH);
this.width = newSize[0];
this.height = newSize[1];
document.getElementById('imageDiv').appendChild(img);
};
}
for (var i = 0; i < image_list.length; i++) {
injectAndResize(image_list[i]);
}
关于javascript - 如何在 JavaScript 中调整图像大小和显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37909627/