jquery - jQuery append 函数表现异步
问题描述
我有这个代码
$("#addr").append("<ul>");
$(data.customer).each( function() {
$("#addr").append("<li><div><b><i><u>
CUSTOMER ID </u></i></b>: "+this.custId+"<br>"+
"<b><u>customer Phone</u></b>"+this.custPhone+"<br>");
$("#addr").append("</div></li></br></br>");
});
$("#addr").append("<p>hiiielajekf</p></ul>");
但是在我的浏览器中,<ul>
是空的,并且所有列表项都在之后开始<ul></ul>
谁能指出我的错误?
解决方案
您正在考虑标记,但这不是您要处理的。你正在处理一个对象树。$("#addr").append("<ul>")
创建并附加一个ul
元素,它不只是开始一个。类似地,稍后你有一个<li>...
inappend
和</li>
另一个,这不是 DOM(和 jQuery)的工作方式。你传入的每个单独的字符串append
都必须是一个完整的、格式良好的 HTML 片段(具有平衡的开始和结束标签),除了如果你只是这样做.append("<tag>")
,jQuery 会像你一样对待它.append("<tag></tag>")
。
要么将整个内容构建为字符串,然后一次性将其全部附加,要么使用对象代替。
做一个大字符串,假设data.customer
是一个数组(并且由于某种原因你需要坚持 ES5 级别的特性):
$("#addr").append(
"<ul>" +
data.customer.map(function(customer) {
return "<li>" +
"<div>" +
"<b><i><u> CUSTOMER ID </u></i></b>: " +
this.custId + "<br>" +
"<b><u>customer Phone</u></b>: " +
this.custPhone + "<br>"
"</div>" +
"</li>;
}) +
"</ul>"
);
$("#addr").append("<p>hiiielajekf</p></ul>");
或li
分别构建:
var ul = $("<ul>");
data.customer.forEach(function(customer) {
ul.append("<li>" +
"<div>" +
"<b><i><u> CUSTOMER ID </u></i></b>: " +
this.custId + "<br>" +
"<b><u>customer Phone</u></b>: " +
this.custPhone + "<br>"
"</div>" +
"</li>");
});
$("#addr").append(ul);
$("#addr").append("<p>hiiielajekf</p></ul>");