我无法完全按照问题中的要求重现问题。在带有 JQuery 1.6(以及 3.3.1)的 Chrome 72 中,将该响应放入字符串并附加到 tbody 实际上对我来说效果很好
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.js"></script>
<script type="text/javascript">
function test() {
var template = '<tr><td><input value="Blah"></td><td>col2</td></tr>';
var obj = $("#myTable");
alert(template);
obj.find('tbody').append(template);
}
</script>
</head>
<body>
<table id="myTable" border="1">
<tbody>
<tr><td>foo</td><td>bar</td></tr>
</tbody>
</table>
<button type="button" onclick="test();">Test</button>
</body>
</html>
话虽如此,首先是什么导致我提出这个问题(并且让我认为我的回答可能仍然对其他人发现这个问题有一些小的帮助)是一个非常相似的问题,即试图从响应中提取一些 tr 元素并插入将它们放入我页面上的现有表格中,看到所有 tr 和 td 都以 OP 描述的方式被剥离。
我的情况是返回包含两组行的响应,一组在 tbody 中,另一组在 tfooter 中,所以我想分别将子节点从 tbody 和 tfooter 复制到我页面表中的各自目标节点中.
这看到我首先将响应文本解析为节点,以便能够在其中找到所需的节点子集以提取并复制到我的表中(而不是像 OP 那样直接将其全部附加)。
尝试这样做,我突然发现在解析响应时所有的 tr,td 都被剥离了。
这是因为我的响应没有用表格标签包装它们(因此解决方案是更改响应以用表格标签(而不是 div)包围它们)然后允许响应成功解析为没有 tr 的 html, td 剥离。
我怀疑这种剥离是 jquery 如何使用浏览器的本机 DOM 内容将 html 字符串解析为实际节点的副作用。当您只是将一个充满 trs 的字符串直接附加到 tbody 中时,这很好,因为 trs 属于 tbody - 他们和他们的朋友在一起,一切都是阳光和玫瑰,但首先解析它们意味着 jquery 在幕后设置了将字符串放入 div 的 innerHTML 中,其中未列出的 trs 和 tds 不在其满意的位置,并且浏览器不喜欢这样。
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript">
theBodyPart
= '<tbody id="resultBody">'
+ '<tr><td><input value="Hello"></td><td>World</td></tr>'
+ '<tr><td>abc</td><td>123</td></tr>'
+ '</tbody>';
//An outer node is needed for the jquery find() (because find doesnt include the start node in its search)
badResponse = '<div>' + theBodyPart + '</div>';
goodResponse = '<table>' + theBodyPart + '</table>';
function replaceBody(response) {
var parsedResponse = $( response );
alert('parsedResponse=' + parsedResponse.html()); //<-- you can see the tr, td stripping of badResponse here
//parse the html, search for node, use first result
//(this fails if wrapped in a div instead of a table because the tbody was stripped!)
var resultBody = parsedResponse.find("#resultBody")[0];
if(resultBody) {
$( "#myBody" ).html( $(resultBody).html());
} else {
alert('resultBody not found');
}
}
</script>
</head>
<body>
<table border="1">
<thead>
<tr><th>Foo</th><th>Bar</th></tr>
</thead>
<tbody id="myBody">
<tr><td>old1</td><td>old2</td></tr>
</tbody>
</table>
<button type="button" onclick="replaceBody(badResponse);">Bad</button>
<button type="button" onclick="replaceBody(goodResponse);">Good</button><br/>
<div id="message"></div>
</body>
</html>
但是我仍然不知道为什么 OP 失败了,因为他们在执行追加之前没有尝试解析和提取响应!