所以在我的 php 文件中,组是从上到下列出的。我想从左到右列出它们,然后从下一行开始,所以它们都以网格格式在页面上很好地显示。我怎样才能添加 html/css 来做到这一点?
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/