大家好!我似乎遇到了异步操作问题,我不知道如何处理。
我希望显示此代码
Category 1,
Items of category 1
Category 2,
Items of category 2
Category 3,
Items of category 3
我得到的是:
Category 1,
Category 2,
Category 3,
Items of category 1
Items of category 2
Items of category 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;
}
通过同步附加 header ,可以保证它们的顺序与原始 subheaders
一致。无论 ajax 响应的接收顺序如何。
关于jquery - 如何在 '.append()'循环内同步 'for'和ajax查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48012487/