我正在使用 jQuery 尝试从 JSON 对象构建 Web 应用程序的表(使用 asyncgetJson
调用),并且我很难了解执行顺序的底部。
我的JS是:
//create table header
$('#peopleDirectory').append(
"<table><thead><tr><th>column header!</th>"
+"</tr></thead><tbody>"
);
//iterate through list to create table row:
$.each(jsonArray.members, function(i, membObj) {
$('#peopleDirectory').append(
"<tr>"
+ "<td>" + membObj.name + "</td>"
+ "</tr>"
);
});
//end table
$('#peopleDirectory').append("</tbody></table>");
我创建表和标题行,然后迭代返回的 JSON 以创建表行,然后关闭表。但是,如果我使用 jQuery$('#peopleDirectory').html()
然后它生成表头,然后关闭表,然后附加 JSON 中的行(并且表无法正确显示)
谁能帮我解释为什么它按这个顺序执行附加?
这里的问题可能是您无法像您所做的那样将部分 HTML 附加到元素。当您追加时<table><tbody>
,浏览器实际上也会关闭标签。然后,当您附加tr
等,它不再位于表格内,浏览器将再次尝试纠正它,生成损坏的标记。
你需要先构造整个标记并且只有在那之后才添加它。
像这样的东西应该有效:
var html = "<table><thead><tr><th>column header!</th>"
+ "</tr></thead><tbody>";
$.each(jsonArray.members, function(i, membObj) {
html += "<tr>"
+ "<td>" + membObj.name + "</td>"
+ "</tr>";
});
html += "</tbody></table>";
$('#peopleDirectory').append(html);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)