JS 合并表格
    		       		warning:
    		            这篇文章距离上次修改已过449天,其中的内容可能已经有所变动。
    		        
        		                
                要在JavaScript中合并两个表格,您可以遍历每个表格的行,并将这些行添加到一个新的表格中。以下是一个简单的函数,用于合并两个表格:
function mergeTables(table1, table2) {
  const newTable = document.createElement('table');
  // 复制表格的结构,包括 thead、tbody 和 tfoot
  table1.querySelectorAll('*').forEach(node => {
    newTable.appendChild(node.cloneNode(true));
  });
  table2.querySelectorAll('tr').forEach(row => {
    newTable.appendChild(row.cloneNode(true));
  });
  return newTable;
}
 
// 使用示例
const table1 = document.getElementById('table1');
const table2 = document.getElementById('table2');
const mergedTable = mergeTables(table1, table2);
 
// 将合并后的表格添加到文档中
document.body.appendChild(mergedTable);确保在调用mergeTables函数之前,两个表格都已经存在于DOM中,并且它们具有相同的结构(即有相同数量和类型的<thead>、<tbody>和<tfoot>元素)。这个函数会返回一个新的表格元素,您可以将它插入到文档中的任何位置。
评论已关闭