如何使用JavaScript为HTML表格添加表头为GroupN依次递增的新列
你可以通过新增分组列计数器、区分表头和普通行的显示文本实现需求,修改后的代码如下:
修改后的JS代码
// 新增计数器,记录已添加的分组列数量 let groupCount = 0; // append column to the HTML table function appendColumn() { groupCount += 1; var tbl = document.getElementById('member_table'), // table reference i; // open loop for each row and append cell for (i = 0; i < tbl.rows.length; i++) { // 表头行(第0行)显示Group+序号,其他行保持原有逻辑 const cellText = i === 0 ? `Group${groupCount}` : i; createCell(tbl.rows[i].insertCell(tbl.rows[i].cells.length), cellText, 'col'); } } // create DIV element and append to the table cell function createCell(cell, text, style) { var div = document.createElement('div'), // create DIV element txt = document.createTextNode(text); // create text node div.appendChild(txt); // append text node to the DIV div.setAttribute('class', style); // set DIV class attribute div.setAttribute('className', style); // set DIV class attribute for IE (?!) cell.appendChild(div); // append DIV to the table cell }
你的CSS和HTML代码不需要做任何修改,直接复用即可。
内容的提问来源于stack exchange,提问作者terry5546
相关产品推荐
相关产品推荐

