Javascript/jQuery执行顺序问题
我正在使用jQuery尝试从JSON对象(使用asyncJavascript/jQuery执行顺序问题,javascript,jquery,Javascript,Jquery,我正在使用jQuery尝试从JSON对象(使用asyncgetJson调用)为web应用程序构造一个表,我很难找到执行顺序的底部 我的JS是: //create table header $('#peopleDirectory').append( "<table><thead><tr><th>column header!</th>" +"</tr></thead><tbody>" );
getJson
调用)为web应用程序构造一个表,我很难找到执行顺序的底部
我的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>");
//创建表头
$('#peopleDirectory')。追加(
“列标题!”
+""
);
//遍历列表以创建表行:
$.each(jsonArray.members,function(i,membObj){
$('#peopleDirectory')。追加(
""
+“”+membObj.name+“”
+ ""
);
});
//端台
$('#peopleDirectory')。追加(“”);
我创建表和标题行,然后在关闭表之前迭代返回的JSON以创建表行。但是,如果我使用jQuery$(“#peopleDirectory').html()
,那么它会生成表头,然后关闭表,然后追加JSON中的行(并且表显示不正确)
有人能帮我解释一下为什么它会按这种顺序执行附加吗?这里的问题可能是您不能像现在这样将部分HTML附加到元素中。当您附加
时,浏览器实际上也会关闭标记。然后,当您附加tr
s等时,它不再在表中,浏览器将再次尝试更正它,生成损坏的标记
您需要首先构造整个标记,然后再附加它
像这样的方法应该会奏效:
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);
var html=“列标题!”
+ "";
$.each(jsonArray.members,function(i,membObj){
html+=“”
+“”+membObj.name+“”
+ "";
});
html+=“”;
$('#peopleDirectory').append(html);
太棒了,谢谢-我当时看错了方向,以为它是按奇怪的顺序执行的。这已经非常有效了。