无法在循环中获取值

时间:2016-02-14 16:23:59

标签: javascript

window.onload = function(){
    for(var b=0;b<2;b++){
        var imgc = new Image();
        imgc.src = '../images/' + b + '.jpg';
        imgc.height = 200;
        divv.appendChild(imgc);
        alert(document.getElementsByTagName('img')[b].width);
    }
}

当警报在for循环内时,图像的大小不会发出警报。当我将警报移动到onclick时,它会显示出来。我希望你能帮助我。

2 个答案:

答案 0 :(得分:-1)

这个问题可能会被回答数百次。 您必须在实际加载图像之前等待。

之后,您可以提醒图像的宽度。 因此,您必须使用图像的onload - 函数

window.onload = function(){
    for(b=0;b<2;b++){
        var imgc = new Image();


        // note the selfinvoking function which is immediately called with b as a parameter.
        // inside the function b is now a local variable and will not change even if the outer b does
        // you ofc can name the local b as you want
        imgc.onload = (function(b){

          return function(){

            alert(document.getElementsByTagName('img')[b].width)

          }

        })(b)

        imgc.src = '../images/' + b + '.jpg';
        imgc.height = 200;
        divv.appendChild(imgc);
    }
}

您只需从刚刚创建的对象中获取宽度就更容易了 - 因此无需从dom获取数据:

window.onload = function(){
    for(b=0;b<2;b++){
        var imgc = new Image();

        // note the selfinvling function which is immediately called with b as a parameter.
        // inside the function b is now a local variable and will not change even if the outer b does
        // you ofc can name the local b as you want
        imgc.onload = (function(img){

          return function(){

            alert(img.width)

          }

        })(imgc)

        imgc.src = '../images/' + b + '.jpg';
        imgc.height = 200;
        divv.appendChild(imgc);
    }
}

答案 1 :(得分:-2)

现在我假设您希望您的图像在一定的时间间隔后加载,因为如果您没有设置间隔,函数将立即加载最后一张图像,因为它会很快。如果你不想要2秒间隔,只需在代码中将'2000'更改为'0'...希望它有所帮助:

var imgc = new Image();
var b=0;
window.onload = function(){ 
var s=setInterval(imgloader,2000);
}

function imgloader()
{
imgc.src = '../images/' + b + '.jpg';
imgc.height = 200; 
div.appendChild(imgc);
alert(
document.getElementsByTagName('img')[b].width);
b++;
if(b==2){
 clearInterval(s);
}
}