我想在我的网页上显示一些项目的一部分。我有一个项目名称数组和 html 文件中的一些相应数据,如下例所示。我有一个按钮,其中包含一些预览内容,如果用户单击该按钮,它将打开包含所有项目详细信息的完整容器。
为此,我想反向循环切片数组,并将代码添加到网页上的 div 元素前面。内容通常加载得很好,但有时当我刷新页面时,它会以与数组中定义的顺序不同的顺序显示预览。此外,有时“previewtitle”和“previewcontent”返回未定义,但并非总是如此。我在这里做错了什么?
我想在每次刷新时以相同的顺序动态地添加项目。
var $projectNames = [ "coolprojecthere", "andanotherone", "moreprojects", "lastone" ];
projects/coolprojecthere.html 看起来像这样:
<div id="title">Project title here</div>
<div id="content">Content html here</div>
projects/previews/coolprojecthere.html 看起来像这样:
<div id="title">Project title here</div>
<div id="content">Content text here</div>
我像这样循环它们以将它们添加到前面:
$projectNames = $projectNames.slice(0, 7);
$.each($projectNames.reverse(), function (index, projectname) {
var previewtitle, previewcontent;
$.get("projects/previews/" + projectname + ".html", function (prevdata) {
previewtitle = $(prevdata).filter('#title').text();
previewcontent = $(prevdata).filter('#content').text();
});
$.get("projects/" + projectname + ".html", function (data) {
var project = "<section id=\"project\" class=\"\"> \
<t>" + previewtitle + "</t><br /> \
<p>" + previewcontent + "</p> \
</div> \
<div class=\"content\"> \
<h5>" + $(data).filter('#title').text() + "</h5> \
<div class=\"content-container\">"
+ $(data).filter('#content').html() +
"</div> \
</div> \
</section>"
$('#main-container').prepend(project);
});
最佳答案
来自jQuery Documentation您必须将 async
选项指定为 false
才能获取同步 AJAX 请求。
$.ajax({ url: 'projects/previews/" + projectname + ".html',
async: false,
dataType: 'json',
success: function(data) {
// your code here
}
});
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false.
否则,您也可以进行 jQuery 的 AJAX 设置,并通过调用一次将其设置为同步模式(在初始代码之上):
jQuery.ajaxSetup({async:false});
它将在同步模式中执行所有进一步的 AJAX 调用。您可以像以前一样继续使用 jQuery.get();
方法。
Note: Please read Felix Kling's answer, about when synchronous calls might be a bad idea.
关于javascript - 在循环数组时使用 jQuery .get() 前置的元素在页面刷新时以不同的顺序加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23843089/