jQuery将单元格拆分为多行

p8h8hvxi  于 2023-01-25  发布在  jQuery
关注(0)|答案(1)|浏览(193)

我想用一个tr拆分一个表,单元格必须拆分成两半,然后放到下一行。
示例:

<table>
  <tr>
   <td>
     1 Content content Content content Content content Content content
     2 Content content Content content Content content Content content
     3 Content content Content content Content content Content content
     4 Content content Content content Content content Content content
   </td> 
  </tr>
</table>

结果输入:

<table>
  <tr>
   <td>
     1 Content content Content content Content content Content content
     2 Content content Content content Content content Content content
   </td> 
  </tr>
  <tr>
   <td>
     3 Content content Content content Content content Content content
     4 Content content Content content Content content Content content
   </td> 
  </tr>
</table>

如果是多个td,则将具有多个td的行全部拆分为两半

dy1byipe

dy1byipe1#

鉴于我所掌握的最少信息,您可以尝试以下操作

const tableCells = document.querySelectorAll("table tbody tr td")
tableCells.forEach(cell => {
  const content = cell.textContent.trim().split(/\r?\n/);
  if (content.length > 1) {
    cell.textContent = content.slice(0,content.length/2).join('\n')
    const newRow = document.createElement('tr')
    newRow.innerHTML = `<td>${content.slice(content.length/2).join('\n')}</td>`
    const parentRow = cell.closest('tr');
    parentRow.parentNode.insertBefore(newRow, parentRow.nextSibling);
  }
  
})
td { border: 1px solid black; white-space: pre; }
<table>
  <tbody>
    <tr>
      <td>
1 Content content Content content Content content Content content
2 Content content Content content Content content Content content
3 Content content Content content Content content Content content
4 Content content Content content Content content Content content
      </td>
    </tr>
    <tr>
      <td>
1 Content content Content content Content content Content content
2 Content content Content content Content content Content content
3 Content content Content content Content content Content content
4 Content content Content content Content content Content content
      </td>
    </tr>
    <tbody>
</table>

相关问题