开发者

Problem with "document.write()" an Image Array in JavaScript

开发者 https://www.devze.com 2023-01-29 22:01 出处:网络
Am trying to write using document.write() an image at the time from my array. However it does not display any...

Am trying to write using document.write() an image at the time from my array. However it does not display any...

// *** Temporal variables
    var i = 0;
    var j = 0;
    var x = 0;

    // Create basic linear array
    var ImgArray = []

    // Do the 2D array for each or the linear array slots
    for (i=0; i < 4 ; i++) {
        ImgArray[i] = []
    }

    // Load the images
    x = 0;
    for(i=0; i < 4 ; i++) { 
        for(j=0; j < 4 ; j++) { 
          ImgArray[i][j] = new Image();
          ImgArray[i][j] = "Images/" + x + ".jpg";
          document.write("<img id= " + x + " 开发者_运维技巧img src=ImgArray[i][j]  width='120'   height='120'/>");
          x = x + 1;
        }
        document.write("<br>");
    }

What am I doing wrong?


Looks like your JavaScript isn't quite right...

document.write('<img id="' + x + '" src="' + ImgArray[i][j] + '" width="120" height="120"/>');


It looks like you're trying to do image preloading by using new Image(), but then you immediately write out an image element with the same src using document.write(), so the image will not have preloaded and you get no benefit. I also suspect you're missing a .src on one line in the inner loop:

ImgArray[i][j].src = "Images/" + x + ".jpg";

This looping to create image elements would be best done server-side when generating the HTML, but assuming that's not an option, you could lose the ImgArray variable completely:

x = 0;
for(i=0; i < 4; i++) { 
    for(j=0; j < 4; j++) { 
        document.write("<img id='" + x + "' src='Images/" + x + ".jpg' width='120' height='120'>");
        x = x + 1;
    }
    document.write("<br>");
}


document.write writes any input the the location of script element. Try this instead:

in body

<div id="imageContainer"></div>

in your script, gather all output to a variable, say contentVariable, and then

document.getElementById("imageContainer").innerHTML = contentVariable;

note:

It's bad practice to use document.write and even innertml for appending elements to dom. use document.createElement and element.appendChild for dom manupilation.

0

精彩评论

暂无评论...
验证码 换一张
取 消