javascript - 使用页面中的内容插入表格等
问题描述
我想从列表中获取内容并将其转换为表格,插入一些我将编写的内容并对齐此表格
我可以轻松对齐并且已经有了列表,但是我无法将其转换为表格
这是清单
<ul>
<li>Success</li>
<li>SuccessWithRemarks</li>
<li>InvalidInputData</li>
<li>UnavailableData</li>
<li>EntityNotFound</li>
<li>InvalidParameters</li>
<li>ParametersNotSupported</li>
<li>RemoteSystemUnavailable</li>
<li>Timeout</li>
<li>AttemptsLimitReached</li>
<li>RemoteSystemError</li>
<li>AsyncExecutionInProgress</li>
<li>InsufficientBalance</li>
<li>SimultaneousTransactionsLimitReached</li>
<li>TransactionUnavailable</li>
<li>AccessDenied</li>
<li>TransactionCancelled</li>
<li>InternalError</li>
</ul>
只需将其变成具有更多 2 或 3 行的表格
解决方案
实现一个函数,它接受li
标签并将内容转换为表格
function turnIntoTable(input, rowCount) {
var output = "<table><tbody>";
var rows = [];
for (var i = 0; i < rowCount; i++) rows.push([]);
var index = 0;
for (var item of input) {
rows[index % rowCount].push("<td>" + item.innerText + "</td>");
index = (index + 1) % rowCount;
}
for (var rowIndex = 0; rowIndex < rows.length; rowIndex++) {
if ((rowIndex > 0) && (rows[rowIndex].length < rows[rowIndex - 1].length)) rows[rowIndex].push("<td></td>");
output += "<tr>" + rows[rowIndex].join("") + "</tr>";
}
output += "</tbody></table>";
return output;
}
并称之为:
targetTag.innerHTML = turnIntoTable(document.querySelectorAll("li"), 3);
推荐阅读
- java - 导入 Spring Boot 启动项目时出现 Pom.xml 错误
- java - 爪哇。流损坏异常。反序列化
- visual-studio - Visual Studio 的设计视图中的图标/文本大小太大
- swift - 如何使for-in循环等待数据获取功能完成
- c# - 在 Windows 服务器的子目录中安装 Wordpress 以及 asp.net
- r - 在R中将行转换为列
- django - 如何提高django过滤条件的速度?
- swift - 当我绑定它的值时,SwiftUI TextField 的行为很奇怪(不能输入中文,偶尔退格会跳过一个字符)
- php - php循环向数据库添加额外数据
- android-recyclerview - 我正在尝试将我正在关注的书中的代码添加到我正在编写的现有代码中