首页 > 解决方案 > 使用页面中的内容插入表格等

问题描述

我想从列表中获取内容并将其转换为表格,插入一些我将编写的内容并对齐此表格

我可以轻松对齐并且已经有了列表,但是我无法将其转换为表格

这是清单

<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 行的表格

标签: javascriptjqueryhtmlcss

解决方案


实现一个函数,它接受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);

推荐阅读