我使用insertAfter
(根据How to do insert After() in JavaScript without using a library?),但就我而言,它并不起作用。
为什么?
<!doctype html>
<html lang="en">
<head></head>
<body>
<table id="myTable">
<tbody>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<script>
function insertAfter(newNode, referenceNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
_table = document.getElementById("myTable");
_tbody = _table.getElementsByTagName("tbody")[0];
n = _tbody.getElementsByTagName("TR").length;
_referenceNode = _tbody.getElementsByTagName("TR")[n - 1]
_newTR = "<tr><td>A very complex table<td></td><td>much more complex than in this example</td></tr>";
parser = new DOMParser()
_newNode = parser.parseFromString(_newTR, "text/xml");
insertAfter(_newNode, _referenceNode);
</script>
</body>
</html>
答案 0 :(得分:2)
_newNode
是一个XML文档。您无法像这样直接在{1}}中插入#document
。 (否则您会收到此错误:Uncaught HierarchyRequestError: Failed to execute 'insertBefore' on 'Node': Nodes of type '#document' may not be inserted inside nodes of type 'TBODY'.
)
尝试使用
insertAfter(_newNode.childNodes[0], _referenceNode);
因为XML文档的第一个子元素是您之后的元素。
此外,您的HTML无效。使用:
_newTR = "<tr><td>A very complex table</td><td>much more complex than in this example</td></tr>";
不
_newTR = "<tr><td>A very complex table<td></td><td>much more complex than in this example</td></tr>";