我有这个 JavaScript 函数来创建一个包含图像单元格的表格:
function Draw(array) {
// get the reference for the body
var body = document.getElementsByTagName("body")[0];
document.clear();
// creates a <table> element and a <tbody> element
var tbl = document.createElement("table");
tbl.setAttribute("borderstyle", "1");
var tblBody = document.createElement("tbody");
// creating all cells
for (var j = 0; j < 4; j++) {
// creates a table row
var row = document.createElement("tr");
for (var i = 0; i < 4; i++) {
// Create a <td> element and a text node, make the text
// node the contents of the <td>, and put the <td> at
// the end of the table row
var cell = document.createElement("td");
var cellText = document.createElement(array[4 * j + i]);
cell.appendChild(cellText);
row.appendChild(cell);
}
// add the row to the end of the table body
tblBody.appendChild(row);
}
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 2;
tbl.setAttribute("border", "2");
}
但在
var cellText = document.createElement(array[4 * j + i]);
cell.appendChild(cellText);
row.appendChild(cell);
cell.appendChild(cellText);
不起作用!
我不知道为什么,也不知道如何解决!
更新 a 数组是这样的:
var a = Array(16);
for (var i = 0; i < 16; i++) {
a[i] = '<img src="' + i + '.jpg" />';
}
最佳答案
更新答案
回复您的评论:
It just put a text. it means I see the text of
<img src ...
not the image!
如果您告诉我们 array[4 * j + i]
将会很有用包含标记(例如,在问题中包含一个示例)。
如果数组包含标记,您不想创建任何类型的新节点。相反,分配给 innerHTML
表格单元格的:
cell.innerHTML = array[4 * j + i];
row.appendChild(cell);
当您分配给 innerHTML
时,浏览器解析标记并将相关内容添加到元素中。
原始答案在下面的评论之前和 array
之前给出的内容是:
要创建文本节点,请使用 createTextNode
,不是createElement
。所以:
// Change here ---------v
var cellText = document.createTextNode(array[4 * j + i]);
cell.appendChild(cellText);
row.appendChild(cell);
假设array[4 * j + i]
是"Hi there"
。您的document.createElement(array[4 * j + i])
调用要求 DOM 创建一个标签名称为 Hi there
的元素 ,正如document.createElement('div')
那样要求它创建一个标签名称为 div
的元素.
关于javascript - 为什么表的 td node.appendChild 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10569935/