我正在尝试使用 for 循环创建一些 div。我正在使用 .append() 和 .clone 方法,但 div 的顺序错误。即使当我在循环之前创建div时,在index.html中,第一个div(类news0)是在最后一个div(类news3)之后生成的,这应该是最后一个。我该如何解决这个问题?
$news.ready(function () {
var query = [];
console.log(query);
$.ajax({
url: baseUri + "news",
data: {q: query},
success: showNews
});
return false;
});
function showNews(response) {
var news = response[0];
console.log(news);
$news.append($div);
$div.attr('class', 'news' + 0);
$div.append($h1);
$div.append($h2);
$div.append($h3);
$div.append($p);
$h1.html(news.title);
$h2.html(news.author);
$h3.html(news.date);
$p.html(news.body);
for (var i = 1; i < response.length; i++) {
news = response[i];
$news.append($div.clone());
$div.attr('class', 'news' + i);
$div.append($h1);
$div.append($h2);
$div.append($h3);
$div.append($p);
$h1.html(news.title);
$h2.html(news.author);
$h3.html(news.date);
$p.html(news.body);
}
}
最佳答案
由于 javascript for 循环的异步性质,您的情况下 div
的顺序不合适。你可以做的是在jquery中使用$.each
函数,它是同步
,因此会给你想要的输出
带有 $.each()
循环的函数将类似于
function showNews(response) {
var news = response[0];
console.log(news);
$news.append($div);
$div.attr('class', 'news' + 0);
$div.append($h1);
$div.append($h2);
$div.append($h3);
$div.append($p);
$h1.html(news.title);
$h2.html(news.author);
$h3.html(news.date);
$p.html(news.body);
$.each(reponse, function(index, news){
if(index > 0) {
$news.append($div.clone());
$div.attr('class', 'news' + i);
$div.append($h1);
$div.append($h2);
$div.append($h3);
$div.append($p);
$h1.html(news.title);
$h2.html(news.author);
$h3.html(news.date);
$p.html(news.body);
}
})
}
关于javascript - 在循环jquery中使用append、clone,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42179878/