javascript - 添加CSS以将表格格式化为网格

标签 javascript css html

所以在我的 php 文件中,组是从上到下列出的。我想从左到右列出它们,然后从下一行开始,所以它们都以网格格式在页面上很好地显示。我怎样才能添加 html/css 来做到这一点? this is what I have right now

Object.keys(cats).forEach(function(Group) {
      let html = '';

      // Append the 'category' header

      html = '<tr>';
      html += '<td><h1>'+"Group"+ Group+'</h1></td>';
      html += '</tr>';
      $('table').append(html);


      // Loop through the results for this 'category'
      cats[Group].forEach(function(element) {

        var names = element.names;

        var img = "<img src=' " + randomImage+ " ' />";

        html = '<tr>';
        html += '<td><p>' + names + '</p></td> ';

        html += '<td><p>' + img + '</p></td>';
        html += '</tr>';
        $('table').append(html);

      });

    });

    });

    </script>

    </body>

    <table> </table>

最佳答案

正如我在评论中建议的那样,您可以为每个组创建一个表(在您的 for 循环中)并将它们附加到一个 id='tables_container' 的 div。

然后在 CSS 中将表格的宽度设置为 33% 并将它们向左浮动,如下所示:

CSS

table{
  width: 33%;
  float: left;
}

JavaScript/JQuery

Object.keys(cats).forEach(function(Group) {
      let html = '';

      //add the table opening tag to the html variable
      html += '<table>';
      //Append the 'category' header
      html += '<tr>';
      html += '<td><h1>'+"Group"+ Group+'</h1></td>';
      html += '</tr>';

      // Loop through the results for this 'category'
      cats[Group].forEach(function(element) {   
        var names = element.names;
        var img = "<img src=' " + randomImage+ " ' />";
        html += '<tr>';
        html += '<td><p>' + names + '</p></td> ';
        html += '<td><p>' + img + '</p></td>';
        html += '</tr>';
      });
      //add the table closing tag to the html variable
      html += '</table>'; 
      //now that our html variable contains the table html for this group we append it to the tables_container
      $('#tables_container').append(html);
});

HTML

而不是 <table>在您的 html 文档中,您将有一个表格容器。

<div id="tables_container"></div>

关于javascript - 添加CSS以将表格格式化为网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53454533/

相关文章:

javascript - AJAX 电子邮件发送不起作用

html - 使用 CSS 屏蔽 div

html - 如何使用 html5 和文件 API 将单个文件从一个客户端浏览器发送到另一个客户端浏览器而不将其保存在服务器 (node.js) 上

jquery - 如何将一个div的内容克隆到另一个div

javascript - Thymeleaf javascript 根据表格中的文本替换图像源

javascript - 根据选择的单选按钮更改按钮链接

javascript - 浏览器插件?

javascript - 每 5 秒将类(class)随机应用于列表项

css - 将左侧菜单附加到主要内容区域

html - 我怎样才能让我的图像淡出?