javascript - Dynamically Split a table cell into multiple columns depending on the comma
问题描述
I have the following HTML Table displays data from the database.
The cell data use btn btn-info
Bootstrap Button element to highlight the Location Visited
Column.
Current Table:
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"/>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Surname</th>
<th scope="col">Location Visited</th>
<th scope="col">Date</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>Mark</td>
<td>Otto</td>
<td>
<span class="btn btn-info">
R-Block, S-Block, Audit-Block
</span>
</td>
<td>June, 24, 2012</td>
</tr>
<tr>
<th scope="row">2</th>
<td>Jacob</td>
<td>Thornton</td>
<td>
<span class="btn btn-info">
T-Block, S-Block, Finance-Block
</span>
</td>
<td>January, 14, 2012</td>
</tr>
<tr>
<th scope="row">3</th>
<td>Parrel</td>
<td>Smith</td>
<td>
<span class="btn btn-info">
R-Block, H-Block,Admin-Block
</span>
</td>
<td>December, 04, 2012</td>
</tr>
</tbody>
</table>
I want the Cell to always split data whenever a comma is loaded in the cell.
I Have tried using Colspan
but I want the CELL Data to split into multiple columns automatically whenever a comma is present. e.g: if the cell has 2 commas columns, there must be two columns/(blocks), and if the cell has 3 commas the column/(blocks) has to be 3 as well.
Desired Output.
解决方案
Here is the snippet
let td = document.getElementById("container");
let string = "T-Block, S-Block, Finance-Block";
let newArray = string.split(",");
newArray.forEach(item => {
let span = document.createElement("span");
span.setAttribute("class", "btn btn-info me-1");
span.innerHTML = item;
td.appendChild(span);
});
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"/>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Surname</th>
<th scope="col">Location Visited</th>
<th scope="col">Date</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>Mark</td>
<td>Otto</td>
<td id="container"></td>
<td>June, 24, 2012</td>
</tr>
</tbody>
</table>
推荐阅读
- django - django 在提交定义之前阻止访问变量
- html - phonegapp中的Html5视频全屏关闭
- r - 如何计算r中字符串中的段数?
- typescript - 错误 TS2300:重复标识符“RequestInfo”
- neo4j - 设置因果集群失败
- computer-vision - 微软计算机视觉 OCR - 拼凑来自区域的线条
- jenkins - 基于Jenkins中用户输入的条件参数
- swift - 如何在 Swift 中使用 PDFkit 搜索 PDF
- sql-server - SSIS 返回不正确的错误
- java - 哪种 MySQL 类型最好存储时间点信息 - Datetime 或 Timestamp