简体   繁体   中英

how can i create an image array, each with a unique id using getElementById in javascript?

Here is the code I have but when I try to use the image reference its value is null . I want to be able to use it to access another image in a table and change the src property to one in the preloadImages array. I have already made the table but I can't get a reference to the individual elements of the preloadImages array. I want each image to have a unique ID using document.getElementById('id') Please help!! Much appreciated!

var preloadImages = new Array();
SIZE = 52;  

for(var h=0; h<SIZE; h++){
    preloadImages[h] = new Image();  
    preloadImages[h].src = h+'.png';
    preloadImages[h].height =100;
    preloadImages[h].width = 70;
    preloadImages[h].id = "cardImage"+h+"";              
    var cardImageRef = document.getElementById("cardImage"+h+"");
    document.write(cardImageRef+'h'); //This line is for testing, it just returns null
}

You cannot use getElementById() unless the element exists in the DOM tree. This modification will add them to DOM:

for(var h=0; h<SIZE; h++){
    preloadImages[h] = new Image(70, 100);        // size here
    preloadImages[h].src = h+ ".png";
    preloadImages[h].id = "cardImage" + h; 

    document.body.appendChild(preloadImages[h]);  // add to DOM, or some parent element

    var cardImageRef = document.getElementById("cardImage" + h);
    document.write(cardImageRef + "h"); //This line is for testing, it just returns null
}

However, since you already have the elements referenced in an array you could simply look the element up there using the index for the id (instead of using an id at all). This tend to be faster if your page layout has several elements.

var image = preloadImages[index];

If you where using images not identifiable by index you could do (but probably not relevant in this case):

function getImage(id) {
   for(var i = 0; i < preloadImages.length; i++) {
     if (preloadImages[i].id === id) return preloadImages[i];
   }
   return null;
}

So you could use it here, for example:

for(var h=0; h<SIZE; h++){
    preloadImages[h] = new Image(70, 100);        // size here
    preloadImages[h].src = h + ".png";
    preloadImages[h].id = "cardImage" + h;              
}

document.write(getImage("cardImage0"));

There's no reason to use IDs here. In general, it's a "code smell" to construct IDs dynamically and then use getElementById to find them in your document. You can instead just work with the elements themselves.

After the code you posted runs, then preloadImages array contains the added elements. You don't need to use getElementById to find the element you just constructed! And as you found out, you can't use it at all until the element is inserted into the DOM, which you're not ready to do yet!

So in your table logic, you can simply insert the images you created directly using the references you already have in preloadImages :

function makeTable(images) {
    var table = document.createElement('table');
    var tr = document.createElement('tr');
    table.appendChild(tr);

    for (var i = 0; i < images.length; i++) {
        var td = document.createElement('td');
        tr.appendChild(td);

        // put the images in the TD
        td.appendChild(images[i]);
    }

    return table; // to be inserted somewhere
}

document.body.appendChild(makeTable(preloadImages));

I think you're getting confused because some people have gotten into the habit of thinking of IDs as the only way of referring to elements. They construct IDs by concatenating strings, then retrieve the element when they need it by using getElementById . In essence, they are using the document itself as a kind of global bag of things from which you retrieve things using ID as a kind of variable name. It's better in such cases to just work with the elements themselves, held in JavaScript variables or arrays.

The function document.getElementById() can only be used to reference elements that have already been added to the DOM.

However, if you wish to reference images by their id you can build an object instead and use the id as a key:

var preloadImages = {};
SIZE = 52;

for(var h = 0; h < SIZE; ++h) {
    var i    = new Image();
    i.id     = 'cardImage' + h;
    i.src    = h + '.png';
    i.width  = 70;
    i.height = 100;

    preloadImages[i.id] = i;
}

Afterwards you can refer to each image object by its id like so:

var img = preloadImages['cardImage2'];
// do something with image
document.body.appendChild(img); // add to page

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM