Table 动态数据一列跨多行

原创 luoyiming 随笔 html+js+css 127阅读 2018-07-06 16:43:17 举报

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<title>table</title>
<style type="text/css">
table {
border-collapse: collapse;
width: 100%;
}
table th{padding: 8px; background: #dfdfdf; font-weight: bold; border: 1px solid #ccc; }
table td {
border: 1px solid #ccc;
padding: 8px;
}
}
</style>
</head>

<body>
<div id="myTable"></div>
</body>
<script type="text/javascript">
function TableRowSpan(list) {

let topitem = {};
for (let i = 0, length = list.length; i < length; i++) {
    let item = list[i];
    for (let td in item) {
        if (item[td] == topitem[td]) {
            item[td] = null;
        } else {
            topitem[td] = item[td];
        }
    }
}

let footItem = {};
for (let j = list.length - 1; j >= 0; j--) {
    let item = list[j];
    for (let td in item) {
        if (footItem[td] == null) {
            footItem[td] = 1;
        }
        if (item[td] == null) {
            footItem[td] = footItem[td] + 1;
            item[td + '_row'] = 1;
        } else {

            item[td + '_row'] = footItem[td];
            footItem[td] = 1;
        }
    }
}
return list;

}

var box = document.getElementById('myTable');

let data = [{
id: 1,
title: '标题一',
author: '李白',
contnet: '床前明月光'
},
{
id: 2,
title: '标题二',
author: '李白',
contnet: '疑是地上霜'
},
{
id: 3,
title: '标题二',
author: '杜甫',
contnet: '疑是地上霜'
},
{
id: 4,
title: '标题三',
author: '杜甫',
contnet: '举头望明月',
},
{
id: 5,
title: '标题三',
author: '杜甫',
contnet: '举头望明月2',
},
{
id: 6,
title: '标题四',
author: '白居易',
contnet: '举头望明月2',
},
{
id: 7,
title: '标题三',
author: '白居易',
contnet: '举头望明月',
},

];

var list = TableRowSpan(data);

var table = '';
for (var i = 0, length = list.length; i < length; i++) {
var item = list[i];
var title = item.title != null ? '<td rowspan="' + item.title_row + '">' + item.title + '</td>' : '';
var author = item.author != null ? '<td rowspan="' + item.author_row + '">' + item.author + '</td>' : '';
var contnet = item.contnet != null ? '<td rowspan="' + item.contnet_row + '">' + item.contnet + '</td>' : '';

table += '<tr><td>' + item.id + '</td>' + title + author + contnet+ '</tr>';

}
table = '<table><tr><th>ID</th><th>标题</th><th>作者</th><th>内容</th></tr>' + table + '</table>';

box.innerHTML = table;
</script>

</html>

评论 ( 0 )
最新评论
暂无评论

赶紧努力消灭 0 回复