簡體   English   中英

如何在html表中插入幾個相同的圖像?

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

我正在做一個記憶卡游戲,它必須放在桌子上。 因此,開始時,我需要幾個相同的圖像(紙牌背面)。 我已經插入了圖像,並且已按需加載,這是到目前為止的代碼:

<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循環多次調用該圖像,而不是對其進行硬編碼。 我知道這可能很容易做到,但是我是一個初學者,已經嘗試了幾個小時。

您需要在要存儲圖像的容器中添加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.
}

這是您可以在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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM