我有一个数组数组,其中包含 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 元素吗?
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/