我正在使用jQuery尝试从JSON对象构建一个Web应用程序表(使用异步getJson
调用),并且我很难找到执行顺序的底部。
我的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中的行(并且表格没有正确显示)
任何人都可以帮我解释为什么它按此顺序执行追加?
答案 0 :(得分:10)
这里的问题可能是您无法将部分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);