如何在html表中插入多个相同的图像

How to insert several of the same image in a html table?

本文关键字:图像 插入 html      更新时间:2023-09-26

我正在制作一个存储卡游戏,它必须在一个表中。因此,首先,我需要几个相同的图像(一张扑克牌的背面)。我已经插入了图像,它应该加载,这是到目前为止的代码:

<table border="1" style="width:100%">
<tr>
    <td>
        <a href="default.asp">
        <img src="back.gif" alt="Please re-load" style="width:200px;height:249px;border:0;">
        </a>
    </td>
</tr>

还需要使用for循环多次调用图像,而不是对其进行硬编码。我知道这可能很容易做到,但我是一个初学者,已经尝试了几个小时了。

以下是如何在for循环中使用纯javascript创建元素。HTML方面,您只需要一个空表来向其添加元素。

var width = 4;
var height = 4;
for (var i = 0; i < height; i++) {
  
  var tr = document.createElement("tr");
  
  for (var j = 0; j < width; j++) {
    var td = document.createElement("td");
    var a = document.createElement("a");
    a.setAttribute("href", "#");
    var img = document.createElement("img");
    img.setAttribute("src", "http://www.bgdf.com/sites/default/files/images/AAAADEnelREAAAAAAM6-JASMALL.preview.jpg");
    a.appendChild(img);
    td.appendChild(a);
    tr.appendChild(td);
  }
  document.getElementById("memoryGame").appendChild(tr);
}
#memoryGame img {
  width: 75px;
  height: 100px;
}
<table id="memoryGame">
</table>

您需要将id="box"添加到要存储图像的内容器中。

document.getElementById('box').innerHTML += '<img src="back.gif" alt="Please re-load" style="width:200px;height:249px;border:0;">';

我会这样做。

https://jsfiddle.net/h6uwpjt1/

for (var i = 0; i < 10; i++) {
      $('#table1 tr').append('<td><a href="default.asp"><img src="back.gif" alt="Please re-load" style="width:200px;height:249px;border:0;"></a></td>')
    }

当然,这取决于每行中需要多少img,但您可以更改代码。假设你每行只想要3个img,然后说

if((i % 3) == 0)
{
   //Append a </tr> to close the existing tr.
   //Append a new <tr> to begin the new row.
}