简体   繁体   中英

Array of images into table- Javascript

I am trying to create a table of 6 images, 2 rows and 3 columns large. I have created an array for all of them in the head of the program. Should it be in the body? The images within the table will later need to be clickable, directing to the same page (ie. google.com). I don't know how to put the images individually into the table that I have created.

<head>
  <script>
    var img = new Array(6);
    img[0] = new (400,200)
    img[0].src"image1.jpg"
  </script
</head>

... and so on for all the rest of the images

<body>
    <table border ="0">
    <tr>
    <td>document.write(img[0]) </td>
    </tr>
    </table>
</body>

... and so on for the rest of the images

You appear to be neglecting DRY - Don't Repeat Yourself. You are repeating code for every image you want to create. Instead, try this:

<script type="text/javascript">
    (function() {
        var images = [
            "image1.jpg",
            "photo.jpg",
            "graphic.png",
            "animation.gif"
        ], columns = 3,
        l = images.length, i,
        table = document.createElement('table'),
        tbody = table.appendChild(document.createElement('tbody')),
        tr, td, img;
        for( i=0; i<l; i++) {
            if( i % columns == 0) tr = tbody.appendChild(document.createElement('tr'));
            tr.appendChild(document.createElement('td'))
              .appendChild(document.createElement('img'))
              .src = images[i];
        }
        document.body.appendChild(table);
    })();
</script>

This will basically insert the table with all the images right where the script is. To add more images, just add more URLs to the array. To change how many are shown on each row, just change the columns variable. This code is more complicated than your original code, but on the other hand it is much more scaleable and easier to modify.

This is one way you could do it:

<td><img id="theImage" /></td>
<script>
 document.getElementById("theImage").src = img[0].src;
</script>

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