javascript - 如何将包含 HTML 元素的数组转换为 Javascript 中的表格?

标签 javascript html

我有一个数组数组,其中包含 HTML 元素,如 <a>我想转换为表格,但我的问题是 HTML 显示为原始文本。

首先我认为这是隐藏双引号的问题,所以我将它们替换为 .replace()

cell.appendChild(document.createTextNode(x[i][j].replace(/"/g, "")));

但看起来 HTML 在 Chrome DevTools DOM 元素中的格式正确:

<td><a href='http://website.org/prod4'>Product4</a></td>

您能告诉我该怎么做才能在表格中显示 HTML 元素吗?

JSFiddle

var orderArray = [
    ["1", "29-Aug-2012", "Product1", "client1"],
    ["2", "29-Aug-2012", "Product2", "client2"],
    ["3", "29-Aug-2012", "Product3", "client3"],
    ["4", "29-Aug-2012", "<a href='http://website.org/prod/'>Product4</a>", "client4"],
    ["5", "29-Aug-2012", "Product5", "client5"]
    ];

function display() {
    // get handle on div
    var table = document.createElement("table");
    for (var i = 0; i < orderArray.length; i++) {
        var row = table.insertRow();
        for (var j = 0; j < orderArray[i].length; j++) {
            var cell = row.insertCell();
            cell.appendChild(document.createTextNode(orderArray[i][j]));
        }
    }
    return table;
}
var container = document.getElementById('container');
container.appendChild(display());

我在这个问题中使用了Bergi提出的代码:how to display array values inside <table> tag?

谢谢,

最佳答案

您可以使用.innerHTML 属性来解决当有 HTML 时解析 HTML 并在没有 HTML 时注入(inject)纯文本的问题。

此外,您可以使用 Array.forEach() 方法作为更简单的循环方式。

var orderArray = [
    ["1", "29-Aug-2012", "Product1", "client1"],
    ["2", "29-Aug-2012", "Product2", "client2"],
    ["3", "29-Aug-2012", "Product3", "client3"],
    ["4", "29-Aug-2012", "<a href='http://website.org/prod4'>Product4</a>", "client4"],
    ["5", "29-Aug-2012", "Product5", "client5"]
];

function display() {
    // get handle on div
    var container = document.getElementById('container');
    
    var table = document.createElement("table");
    
    // Arrays support a forEach method that accepts a callback function
    // to be executed on each item of the array. This function is automatically
    // passed 3 arguments: the current array element, the current index and the array itself.
    // We only need to capture the reference to the array element (value and innerValue in
    // this example).
    orderArray.forEach(function(value) {
        var row = table.insertRow();
        
        value.forEach(function(innerValue) {
            var cell = row.insertCell();
            cell.innerHTML = innerValue;
        });
    });
    
    return table;
}

container.appendChild(display());
td { padding:5px; }
<div id="container"></div>

关于javascript - 如何将包含 HTML 元素的数组转换为 Javascript 中的表格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43428945/

相关文章:

javascript - 如何在 JQuery UI Selectable 上实现切换功能?

Android 正则表达式 HTML

html - 如何在其父元素之前订购子 flex 元素?

javascript - 针对 Grails 后端的 PhoneGap 身份验证模式

javascript - 如何将 div 包裹在用户给定字符串中的每个字母周围

javascript - 如何用ajax响应替换整个html网页?

没有 jQuery 的 JavaScript 日期时间选择器?

html - CSS背景分隔线的困难

javascript - 提交联系回复到电子邮件

javascript - 如何在 $location 参数更改时禁用页面跳转到顶部?