目前我正在制作另一个 html5/javascript 广告。这个使用来自 cookie 的多个数据。为了正确渲染所有内容,我创建了一个 for 循环来获取信息,然后将其发送到另一个函数。
我的问题是它第一次加载太快,因此它跳过了图像。每次我都必须刷新广告才能正确显示。到目前为止,我使用过的所有 onload 函数都失败了(发送了错误的数据,什么也没有发送,或者只有 1 条数据)。
以下是该项目的相关部分:
for (var i=0; i < 3; i++){
pT.push("pT"+[i]);
pM.push("pM"+[i]);
ctx.push("ctxP"+[i]);
cvs.push("cvsP"+[i]);
cvs[i] = document.getElementById('canvas'+[i]);
ctx[i] = cvs[i].getContext('2d');
pT[i] = new Image();
pT[i].onload = function(){
console.log("pT: "+ this.height);
}
pT[i].src = data.products[i].imageUrl;
pM[i] = new Image();
pM[i].onload = function(){
console.log("pM: "+ this.height);
}
pM[i].src = data.products[i].imageUrl;
testing(pT[i], pM[i]);
}
function testing(pThumb, pMain){
console.log(pThumb.height);
}
我想要的是一种方法,以便在所有内容加载完成后发送所有信息。
最佳答案
pT[i].onload = function() {
alert("Image is Loaded, do you thing on the image here");
}
otherFunction(pT,pM);
function otherFunction(pT,pM) {
console.log(pT,pM);
}
pT[i] = new Image();
pT[i].onload = function(){
pM[i] = new Image();
pM[i].onload = function(){
console.log("pM: "+ this.height);
testing(pT[i], pM[i]);
}
}
pT[i].src = data.products[i].imageUrl;
pM[i].src = data.products[i].imageUrl; // this is very ugly but you'll be sure to call your function when both image are ready. Since i'm not the best with Canvas, I will accept any edit for a better code.
关于javascript - 通过for循环发送信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12709235/