javascript - 通过for循环发送信息

标签 javascript html for-loop

目前我正在制作另一个 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/

相关文章:

javascript - Google Chrome 和 Firefox 之间的差异

javascript - jquery - 使用 PHP 自动完成

javascript - 使用 HTML-CSS-JS 在触摸事件上播放 MP3

html - 弄清楚过渡

javascript - 如何创建具有动态 y 轴的图表,取决于 JSON 中的最高值

c - 在 C 中优化康威生命游戏的邻居计数函数

javascript - React js从输入字段获取数据

javascript - 使用 Javascript 和 HTML 表单向 Facebook 提交图像

python - 如何在带有错误处理的 for 循环中进行迭代

python - 优化列表范围内的数字总和