js將一個table的某列轉(zhuǎn)移到另一個table的上
當(dāng)前位置:點晴教程→知識管理交流
→『 技術(shù)文檔交流 』
![]() ![]() <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <script> function moveTableColumn(sourceTableId, targetTableId, columnIndex) { // 1. 獲取源表格和目標(biāo)表格 const sourceTable = document.getElementById(sourceTableId); const targetTable = document.getElementById(targetTableId);
// 2. 校驗表格和列是否存在 if (!sourceTable || !targetTable) { console.error("Source or target table not found."); return; }
const sourceRows = sourceTable.rows; if (sourceRows.length === 0) { console.warn("Source table is empty."); return; }
if (columnIndex < 0 || columnIndex >= sourceRows[0].cells.length) { console.error("Invalid column index."); return; }
// 3. 遍歷源表格的每一行,將指定列的單元格移動到目標(biāo)表格的對應(yīng)行 for (let i = 0; i < sourceRows.length; i++) { const sourceRow = sourceRows[i]; const sourceCell = sourceRow.cells[columnIndex];
// 確保目標(biāo)表格的行數(shù)足夠,如果不夠則創(chuàng)建新的行 if (targetTable.rows.length <= i) { const newTargetRow = targetTable.insertRow(); // 在末尾插入新行 } const targetRow = targetTable.rows[i];
// 將源單元格添加到目標(biāo)表格的行中 targetRow.appendChild(sourceCell); // 移動單元格
// 如果需要復(fù)制單元格,而不是移動,使用以下代碼: // const clonedSourceCell = sourceCell.cloneNode(true); // 克隆節(jié)點(包含子節(jié)點) // targetRow.appendChild(clonedSourceCell); }
// 4. (可選) 移除源表格的空列 (不建議,可能破壞表格結(jié)構(gòu)) // 如果你確實想要移除空列,必須在遍歷后進(jìn)行,并考慮表格結(jié)構(gòu)。 // 移除空列的代碼會比較復(fù)雜,因為需要考慮合并單元格等情況。 // 通常更好的做法是隱藏源表格的列,而不是直接移除。 } </script> <body> <table id="sourceTable" border="1"> <thead> <tr> <th>Column 1</th> <th>Column 2</th> <th>Column 3</th> </tr> </thead> <tbody> <tr> <td>Row 1, Col 1</td> <td>Row 1, Col 2</td> <td>Row 1, Col 3</td> </tr> <tr> <td>Row 2, Col 1</td> <td>Row 2, Col 2</td> <td>Row 2, Col 3</td> </tr> </tbody> </table>
<table id="targetTable" border="1"> <thead> <tr> <th>New Column</th> </tr> </thead> <tbody> </tbody> </table> <button onclick="moveTableColumn('sourceTable', 'targetTable', 1)">Move Column 2</button> </body> </html> 該文章在 2025/4/19 15:50:21 編輯過 |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |