简体   繁体   English

在JavaScript上生成带有图像的表格

[英]Generate table with images on javascript

I want to create a button that produces a 3x3 HTML table meant for a card game, where each cell corresponds to one single image. 我想创建一个按钮,该按钮生成一个3x3 HTML表,用于纸牌游戏,其中每个单元格对应一个单一图像。 For the time being, I'm mainly focusing on filling individual cells with a card number taken from an array element, using a step-by-step rationale. 暂时,我主要集中在逐步方法上,用从数组元素中提取的卡号填充单个单元格。 This is what the final result should look like in HTML, derived from the produced script; 这是从生成的脚本派生的最终结果在HTML中应该是什么样子;

<table style="width:100%"> 
    <tr> 
        <td><img src="1.png"></td> 
        <td><img src="2.png"></td> 
        <td><img src="3.png"></td> 
    </tr> 
    <tr> 
        <td><img src="4.png"></td> 
        <td><img src="5.png"></td> 
        <td><img src="6.png"></td> 
    </tr> 
    <tr> 
        <td><img src="7.png"></td> 
        <td><img src="8.png"></td> 
        <td><img src="9.png"></td> 
    </tr> 
</table>

This is what I'm currently working at, although with not much success 这是我目前正在从事的工作,尽管没有取得太大的成功

<!DOCTYPE html>
<html>
<body>

<table id="1"> 
</table>

<button onclick="createTable()">Create</button>

<script>
function createTable() {
    var deck = [1,2,3,4,5,6,7,8,9];

    function shuffle(o) { //v1.0
      for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
      return o;
    }

    shuffle(deck);
    document.getElementById("1").innerHTML = "<tr><td>" + deck[0] + "</td><td>" + deck[1] + "</td><td>" + deck[2] + "</td></tr>" +
    "<tr><td>" + deck[3] + "</td><td>" + deck[4] + "</td><td>" + deck[5] + "</td></tr>" +
    "<tr><td>" + deck[6] + "</td><td>" + deck[7] + "</td><td>" + deck[8] + "</td></tr>" +
    ;
}
</script>

</body>
</html>

Note The 9-card deck is shuffled using a pretty basic and self-explanatory function. 注意 9张卡片纸牌是使用非常基本且不言自明的功能进行混洗的。

Edit . 编辑 My final version, which is returning broken image. 我的最终版本正在返回损坏的图像。

<!DOCTYPE html>
<html>
<body>

<table id="1"> 
</table>

<button onclick="createTable()">Create</button>

<script>
function createTable() {
    var deck = [1,2,3,4,5,6,7,8,9];

    function shuffle(o) {
      for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
      return o;
    }

    shuffle(deck);
    document.getElementById("1").innerHTML = "<tr><td><img src=" + deck[0] + ".png'></td><td>" + deck[1] + "</td><td>" + deck[2] + "</td></tr>" +
    "<tr><td>" + deck[3] + "</td><td>" + deck[4] + "</td><td>" + deck[5] + "</td></tr>" +
    "<tr><td>" + deck[6] + "</td><td>" + deck[7] + "</td><td>" + deck[8] + "</td></tr>"
    ;
}
</script>

</body>
</html>

After you fix your code by removing the extra + at the last line where you build your html (tr's and td's), you will simply need just to replace 通过在生成html的最后一行(tr和td)中删除多余的+来修复代码后,您只需要替换

"<td>" + deck[0] + "</td>"

by 通过

"<td><img src='" + deck[0] + ".png'></td>"

... and so on for other indexes like deck[1] , deck[2] etc. ...,以此类推,用于其他索引,例如deck[1]deck[2]等。

You have got an extra "+" 您还有一个额外的“ +”号

document.getElementById("1").innerHTML = "<tr><td>" + deck[0] + "</td><td>" + deck[1] + "</td><td>" + deck[2] + "</td></tr>" +
"<tr><td>" + deck[3] + "</td><td>" + deck[4] + "</td><td>" + deck[5] + "</td></tr>" +
"<tr><td>" + deck[6] + "</td><td>" + deck[7] + "</td><td>" + deck[8] + "</td></tr>";

Should work better. 应该更好地工作。

Your shuffle() is pretty convoluted. 您的shuffle()非常复杂。 Let me advise you to write less exotic code. 让我建议您编写更少的外来代码。 Making your code more readable will help to find potential errors. 使代码更具可读性将有助于发现潜在的错误。 Indeed, the problem is not so hard to locate actually: https://stackoverflow.com/a/34471591/1636522 :-) 确实,实际上很难找到问题所在: https : //stackoverflow.com/a/34471591/1636522 :-)

 var deck = [1, 2, 3, 4, 5, 6, 7, 8, 9]; document.write(JSON.stringify(shuffle(deck), 0, 1)); function shuffle (anArray) { var i, j, x, l = anArray.length; for (i = 0; i < l; i++) { j = rdmInt(l); x = anArray[i]; anArray[i] = anArray[j]; anArray[j] = x; } return anArray; } function rdmInt (max) { return Math.floor(Math.random() * max); } 

The same remark applies to your string concatenation: 相同的注释适用于您的字符串连接:

document.getElementById("1").innerHTML = ""
+ "<tr>"
+   "<td><img src=" + deck[0] + ".png'></td>"
+   "<td>" + deck[1] + "</td>"
+   "<td>" + deck[2] + "</td>"
+ "</tr>"
+ "<tr>"
+   "<td>" + deck[3] + "</td>"
+   "<td>" + deck[4] + "</td>"
+   "<td>" + deck[5] + "</td>"
+ "</tr>"
+ "<tr>"
+   "<td>" + deck[6] + "</td>"
+   "<td>" + deck[7] + "</td>"
+   "<td>" + deck[8] + "</td>"
+ "</tr>";

Can you see the error now (line 3)? 您现在可以看到错误(第3行)吗? Here is a fix: 解决方法:

+   "<td><img src=\"" + deck[0] + ".png\"></td>"

You could go even further to avoid repetitions ( dry ): 您甚至可以进一步避免重复( 干燥 ):

 var deck = [ "KNhxd", "7CtbR", "Os8qX", "21SKd", "CWMZC", "43C1X", "lpGvK", "8Wk7W", "Y3JFi" ]; // preserve the global namespace with an IIFE document.body.innerHTML = function () { var ROOT = "http://i.stack.imgur.com/"; function toTable (deck) { var i, html = ""; for (i = 0; i < 3; i++) { html += toTr(deck.slice(i * 3, (i + 1) * 3)); } return "<table>" + html + "</table>"; } function toTr (row) { return "<tr>" + row.map(toTd).join('') + "</tr>"; } function toTd (cell) { return "<td><img src=\\"" + ROOT + cell + ".png\\" /></td>"; } return toTable(deck); }(); 
 body{background:#006600;} img{display:block;width:35px;} 

When I load your code I get this message in the browser console: 加载您的代码时,我在浏览器控制台中收到以下消息:

Uncaught SyntaxError: Unexpected token ; 未捕获到的SyntaxError:意外令牌;

It might help if you update this code: 如果更新以下代码,则可能会有所帮助:

document.getElementById("1").innerHTML = "<tr><td>" + deck[0] + "</td><td>" + deck[1] + "</td><td>" + deck[2] + "</td></tr>" +
    "<tr><td>" + deck[3] + "</td><td>" + deck[4] + "</td><td>" + deck[5] + "</td></tr>" +
    "<tr><td>" + deck[6] + "</td><td>" + deck[7] + "</td><td>" + deck[8] + "</td></tr>" +
    ;

To this: 对此:

document.getElementById("1").innerHTML = "<tr><td>" + deck[0] + "</td><td>" + deck[1] + "</td><td>" + deck[2] + "</td></tr>" +
                "<tr><td>" + deck[3] + "</td><td>" + deck[4] + "</td><td>" + deck[5] + "</td></tr>" +
                "<tr><td>" + deck[6] + "</td><td>" + deck[7] + "</td><td>" + deck[8] + "</td></tr>";

To loop your array and create your table structure with the images, you could do this for example: 要循环数组并使用图像创建表结构,可以执行以下操作:

function createTable() {
    var deck = [1,2,3,4,5,6,7,8,9];

    function shuffle(o) { //v1.0
        for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
        return o;
    }

    shuffle(deck);

    var html = '';
    for (var i = 0; i < deck.length; i++) {
        if (i%3 === 0) {
            html += "<tr>";
        }
        html += '<td><img src="' + deck[i] + '.png"></td>';
        if (i%3 === 2) {
            html += "</tr>";
        }
    }
    document.getElementById("1").innerHTML = html;
}

If you want to create HTML elements, then you do not just write them as a text string and insert into an existing HTML element. 如果要创建HTML元素,则不只是将它们编写为文本字符串并插入现有的HTML元素中。

You create an element node (and text node if applicable) and append that to your existing HTML element. 您创建一个元素节点(和文本节点,如果适用),并将其附加到现有的HTML元素上。

Here is an article on w3 schools about creatung HTML tags with JavaScript. 这是有关W3学校的一篇有关使用JavaScript创建HTML标签的文章。

http://www.w3schools.com/jsref/met_document_createelement.asp http://www.w3schools.com/jsref/met_document_createelement.asp

If your table is always 9 cells then why not just write the HTML out giving each cell a unique id. 如果您的表始终是9个单元格,那么为什么不编写HTML并给每个单元格一个唯一的ID。 Then u could use code similar to what u have. 然后,您可以使用类似于您所拥有的代码。

document.getElementById("cell_1").innerHTML = deck[0];

You would need to include this logic for all 9 cells / values, although you could loop through them like; 您可能需要为所有9个单元格/值都包括此逻辑,尽管您可以像这样遍历它们。

for (i = 0; i < 8; i++) { 
  var cellNo = i + 1;
  document.getElementById("cell_" + cellNo).innerHTML = deck[i];
}

Hope this helps ;) 希望这可以帮助 ;)

In addition to the unnecessary '+' at the end of your innerHTML addition, I would suggest making your code more flexible. 除了在innerHTML添加末尾不必要的“ +”之外,我建议您使代码更灵活。 Instead of adding the data hardcoded to your innerHTML you can do something like this: 您可以执行以下操作,而不是将硬编码的数据添加到您的innerHTML中:

var endOfRowCounter = 0;
var toAppend = "";
deck.forEach(function(card){
   if(endOfRowCounter % 3 == 0) {
        toAppend += "<tr>";
    }

    toAppend += "<td><img src=\"" + card + ".png\"></td>";

    if(endOfRowCounter % 3 == 2)
    {
        toAppend += "</tr>";
    }

    endOfRowCounter++;

});

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

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