我无法让getCategory
函数返回undefined
或false
之外的任何内容。我已经在控制台中介入了所有数据。我仍然不确定使函数调用同步的最佳方法
function getCategory(url) {
if ( url ) {
let message = false
$.ajax({
url: url,
global: false,
type: 'GET',
dataType: 'json',
}).done( function(data) {
message = `<a class="post__category post__link" href="${data[0].link}">${data[0].name}</a>`
return message
})
} else {
return ''
}
}
function posts() {
$.get(WPPosts, data => {
data.forEach( d => {
const excerpt = d.excerpt.rendered.substr(0, characterCount)
const featuredImage = d._links['wp:featuredmedia']
const featuredImageURL = featuredImage ? featuredImage[0].href : ''
const terms = d._links['wp:term']
const category = terms.filter( term => term.taxonomy === 'category')
const categoryURL = category[0].href
let post = `<article class="column">
<div class="decoration decoration__paper decoration__tape decoration__tape--left text-center post">
<a href="${d.link}">
${ getFeaturedImage(featuredImageURL) }
</a>
<h2 class="post__title">${d.title.rendered}</h2>
<p>
${d.date_gmt}
${ getCategory(categoryURL) }
</p>
<div class="post__excerpt">
${excerpt}... <a class="post__link" href="${d.link}">Read more</a>
</div>
</div>
</article>`
post = $.parseHTML( post )
postsWrapper.append(post)
});
})
}
我试图避开{ async: false }
选项
答案 0 :(得分:0)
这里的问题是“getCategory&#39;在第一次接到电话后。
我们可以修改逻辑,这样一旦获得与该锚标记相关的调用,锚标记内的数据就会被加载。
修改锚标记以赋予其唯一ID :(使用您可能想要的任何ID)
<a href="${d.link}" id="${d.link}">
Loding ..${ getFeaturedImage(featuredImageURL,${d.link}) }
</a>
然后修改函数以读取id:
function getCategory(url,id) {
if ( url ) {
let message = '';
$.ajax({
url: url,
global: false,
type: 'GET',
dataType: 'json',
}).done( function(data) {
message = `<a class="post__category post__link" href="${data[0].link}">${data[0].name}</a>`
$("#"+id).html(message ); // append data to anchor tag rather than returning.
})
} else {
$("#"+id).html('');
}
}