简体   繁体   English

图片数组到表中-Javascript

[英]Array of images into table- Javascript

I am trying to create a table of 6 images, 2 rows and 3 columns large. 我正在尝试创建一个包含6张图像,2行和3列的表格。 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). 表格中的图片以后将需要可点击,并指向同一页面(即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. 您似乎忽略了DRY-不要重复自己。 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. 要添加更多图像,只需将更多URL添加到数组。 To change how many are shown on each row, just change the columns variable. 要更改每行显示的数量,只需更改columns变量。 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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