【问题标题】:Sending information through a for loop通过 for 循环发送信息
【发布时间】:2012-10-03 13:10:31
【问题描述】:

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

我想要的是一种方法,以便在所有内容加载完成后发送所有信息。

【问题讨论】:

  • 你尝试使用 onload 监听器了吗?
  • 是的,我有,这导致其余数据无法正确处理,当我尝试修复该问题时,它只会发送数组的一部分而不发送其余部分。可能是我以错误的方式/位置使用它,我仍在学习:)。

标签: javascript html for-loop


【解决方案1】:
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.

【讨论】:

  • 感谢您的回复。我已经尝试过了,它通常可以工作,但在这种情况下它不会(还)。在 for 循环本身中,除了加载和分配它之外,我对图像不做任何事情。在循环结束时,它被发送到另一个函数,在那里它被绘制、动画、调整大小等。
  • 我猜,您是在 .src = data.products[i] 之后设置 onload after 还是 before。图片网址 ??
  • pT[i] = new Image(); pT[i].src = data.products[i].imageUrl; pt[i].onload = function(){ console.log('like this'); } edit 呃,无法获得此评论的标记权
  • 你必须设置onload BEFORE设置源
  • 真的吗?我以为是之后。我会在这个时间之前尝试一下。我将如何做到这一点,以便它还将 3 个不同的图像数据发送到下一个函数?那部分一直是我的瓶颈。
猜你喜欢
  • 2013-12-25
  • 1970-01-01
  • 1970-01-01
  • 2021-11-29
  • 2011-05-26
  • 1970-01-01
  • 2013-09-27
  • 1970-01-01
  • 2015-05-21
相关资源
最近更新 更多