日期:2014-05-16  浏览次数:20286 次

急急急.....chrome对于js的for循环执行问题
我的问题是:原则上,for循环执行一次,最后这行代码就要立即执行:document.getElementById(shotCol).appendChild(div); IE 和 FF 都是正常的,在每次for循环的时候就立即执行了,但是chrome则不是,chrome是把整个for循环跑完之后(i从0-2),然后才统一执行document.getElementById(shotCol).appendChild(div); 这样导致结果就不一样,请问怎么调整? 我要调整到同IE和FF的那种每次for循环的时候就执行的效果,而不是for循环整个都跑完了才统一执行。
for(var i=0; i<2; i++)
{
var bone,btwo,bthree,shotCol;
bone = document.getElementById("cols1").offsetHeight;
btwo = document.getElementById("cols2").offsetHeight;
bthree = document.getElementById("cols3").offsetHeight;
var div = document.createElement("div");
div.className = "img_box";
div.innerHTML = '<img src="images/'+Math.ceil(Math.random()*7)+'.jpg" width="300px" />';
if(bone - btwo <= 0 && bone - bthree <= 0)
{
shotCol = "cols1";
}
else if(btwo - bone <= 0 && btwo - bthree <= 0)
{
shotCol = "cols2";
}
else
{
shotCol = "cols3";
}
document.getElementById(shotCol).appendChild(div);
}

------解决方案--------------------
没测试代码,看不出什么效果,不过你的是for循环,ie和firefox应该也不可能看到1条加完等待一下在添加另外一条的效果吧,这个执行时间肉眼分辨不出来吧。

要是你要哪种效果,可以用setTimeout延时来执行,不用for语句


    var i = 0;

    function addDiv() {
        var bone, btwo, bthree, shotCol;
        bone = document.getElementById("cols1").offsetHeight;
        btwo = document.getElementById("cols2").offsetHeight;
        bthree = document.getElementById("cols3").offsetHeight;
        var div = document.createElement("div");
        div.className = "img_box";
        div.innerHTML = '<img src="images/' + Math.ceil(Math.random() * 7) + '.jpg" width="300px" />';
        if (bone - btwo <= 0 && bone - bthree <= 0) {
            shotCol = "cols1";