今天是个好日子!好像我有异步操作问题,我无法弄清楚如何处理。
我希望这段代码能够显示出来
第1类,
第1类物品
第2类,
第2类物品
第3类,
第3类的项目
而不是我得到的是:
第1类,
第2类,
第3类,
第1类物品
第2类物品
第3类的项目
这是代码:
function showSubheadersMenu (items) {
for (j = 0; j < items.length; j++) {
$("#gallery").append($("<div id=" + items[j].id + " class=\"gallery-item\"><div class=\"item-img\" style=\"background-image:url(" + items[j].better_featured_image.source_url + ")\"></div></div>"));
}
}
function showSingleCategory (subheader) {
$("#gallery").append($("<h3 class=\"subcat\">" + subheader.name + "</h3>"));
$.ajax({
url: "http://localhost/mysite/wp-json/wp/v2/posts?categories=" + subheader.id + "",
dataType: "json",
contentType: "GET",
success: showSubcategoryItems, // Show items in subcategory
error: handleAjaxError
});
}
if (subheaders.length > 0) { //If there are subcategories
for (i = 0; i < subheaders.length; i++) {
showSingleCategory(subheaders[i]);
}
}
由于ajax的异步性,所有'成功'调用都保证在所有<h3>
元素被追加后发生。因此,您描述的症状。
这很容易通过保持对header元素的引用并在showSubcategoryItems(data)
组成的任何内容之后插入来克服。
function showSingleCategory (subheader) {
// keep reference to the appended <h3>
var $header = $("<h3 class=\"subcat\">" + subheader.name + "</h3>").appendTo("#gallery");
$.ajax({
url: "http://localhost/mysite/wp-json/wp/v2/posts?categories=" + subheader.id + "",
dataType: "json",
contentType: "GET",
success: function(data) {
// Show items in subcategory after the corresponding header
$(showSubcategoryItems(data)).insertAfter($header),
}
error: handleAjaxError
});
}
if (subheaders.length > 0) { //If there are subcategories
for (i = 0; i < subheaders.length; i++) {
showSingleCategory(subheaders[i]);
}
}
而showSubcategoryItems()
将具有以下一般形式:
function showSubcategoryItems(data) {
var html = .....; // compose html from data
return html;
}
通过同步附加标题,无论收到ajax响应的顺序如何,它们的顺序都保证与原始的subheaders
一致。
尝试在成功回调中添加<h3>
。这样,它会将每个标题与其各自的项目同时附加,从而为您提供所需的输出。
function showSingleCategory (subheader) {
$.ajax({
url: "http://localhost/mysite/wp-json/wp/v2/posts?categories=" + subheader.id + "",
dataType: "json",
contentType: "GET",
success: function (data) {
$("#gallery").append($("<h3 class=\"subcat\">" + subheader.name + "</h3>"));
showSubcategoryItems(data);
}, // Show items in subcategory
error: handleAjaxError
});
}
if (subheaders.length > 0) { //If there are subcategories
for (i = 0; i < subheaders.length; i++) {
showSingleCategory(subheaders[i]);
}
}