[英]Populate drop down from XML - code executing in wrong order
I am trying to populate a drop down box from an XML file using jQuery. 我正在尝试使用jQuery从XML文件填充下拉框。 When the code is ran it appears to execute in order.
运行代码后,它似乎按顺序执行。
jQuery: jQuery的:
$("#filterButton").click(function() {
var dropdown = new Array();
$.get('../restaurants.xml', function (xmlFile) {
$(xmlFile).find('restaurant').each(function () {
var found = false;
var $restaurant = $(this);
var type = $restaurant.attr("type");
dropdown.forEach(function(arrayValue){
if(arrayValue == type){
found = true;
}
});
if(found == false){
dropdown.push(type);
}
});
});
$('#potentialRestaruants').append('<select>');
dropdown.forEach(function(arrayValue){
$('#potentialRestaruants').append('<option value="' + arrayValue + '">' + arrayValue + '</option>' );
});
$('#potentialRestaruants').append('</select>');
});
However the code is being run in this order: 但是,代码按以下顺序运行:
$("#filterButton").click(function() {
var dropdown = new Array();
then 然后
$('#potentialRestaruants').append('<select>');
dropdown.forEach(function(arrayValue){
$('#potentialRestaruants').append('<option value="' + arrayValue + '">' + arrayValue + '</option>' );
});
$('#potentialRestaruants').append('</select>');
});
then 然后
$.get('../restaurants.xml', function (xmlFile) {
$(xmlFile).find('restaurant').each(function () {
var found = false;
var $restaurant = $(this);
var type = $restaurant.attr("type");
dropdown.forEach(function(arrayValue){
if(arrayValue == type){
found = true;
}
});
if(found == false){
dropdown.push(type);
}
});
});
Why is the code being ran in this order and how can I get to run in the order I need? 为什么代码按此顺序运行,如何才能按需要的顺序运行?
It is being run in the order you describe because the $.get executes asynchronously. 它以您描述的顺序运行,因为$ .get是异步执行的。 So any code that is dependent on the successful execution of the $.get function should also be included at the end of that function Ie the append and second forEach.
因此,任何依赖$ .get函数成功执行的代码也应包括在该函数的末尾,即append和第二个forEach。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.