我在 append <tr>
时遇到了一个奇怪的行为通过 JQuery 将字符串标记添加到表中。每次我 append 我作为字符串生成的行时,它都被放在我的 tbody
之外。 .然后我发现了问题。
如果我像这样 append 它,它工作正常:
$("table").append("<tr><td>Test</td></tr>");
但是,如果我在 <tr>
之前添加空格或换行符, 它将行 append 到 tbody
之外.
$("table").append(" <tr><td>Test</td></tr>");
$("table").append("\n<tr><td>Test</td></tr>");
有趣的是,如果我使用任何其他 Angular 色,它仍然可以正常工作。 这种行为有什么特别的原因吗?
//Works fine without anything before the tr
$("table").append("<tr><td>Second row</td></tr>");
//Works fine also with any character
$("table").append("sdfa<tr><td>Third row</td></tr>");
//Doesn't work when there's an whitespace or newline
$("table").append(" <tr><td>Fourth row</td></tr>");
$("table").append("\n<tr><td>Fifth row</td></tr>");
table tbody td {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td>First row</td>
</tr>
</table>
最佳答案
jQuery 中有一个辅助实用程序,manipulationTarget
,它确定要在何处追加字符串的目标
。具体来说:
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
elem;
}
发生的事情是,当您传入一个开头带有 whitespace
的字符串时,它会创建一个文档片段,其中第一个子节点是 text
节点,而不是 tr
。乱码文本 (sdfa
) 在另一个实用程序方法中被删除。
关于javascript - 为什么在 TR 标记前 append 一个空格或换行符会导致它位于 tbody 之外?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31462471/