2012-10-03 203 views
1

目前我正在制作另一个html5/javascript广告。这一个使用来自cookie的多个数据。为了正确渲染一切,我做了一个for循环来获取信息,然后将它发送给另一个函数。通过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); 
} 

我要的是一个方法,因此,所有的信息获取,当一切都加载完成发送。

+0

您是否尝试过使用onload监听器? –

+0

是的,我导致其余数据不能正确处理,当我试图解决这个问题时,它只会发送数组的一部分,而不是其他数据。可能是因为我以错误的方式/位置使用了它,但我仍然在学习:)。 – Levi

回答

0
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. 
+0

感谢您的回复。我已经尝试过,它通常会工作,但在这种情况下它不会(还)。在for循环本身中,除了加载和分配它之外,我不会对图像做任何事情。在循环结束时,它被发送到另一个函数,它被绘制,动画,重新调整大小等。 – Levi

+0

我在猜测一些事情,你在**或**之前设置了onload **之前** ** .src = data.products [i] .imageUrl ** ?? –

+0

pT [i] = new Image(); pT [i] .src = data.products [i] .imageUrl; pt [i] .onload = function(){ console.log('like this'); } *编辑* Ughh无法获得此评论的标记权 – Levi