这是一个工作良好的JavaScript代码的一部分。 但我想,以显示//练习2行中的变量选项:javascript - 这段代码有什么错误?
if(profId==10){
//alert(profId);
$("#div_sel_residentType").show("slow");
var selectElm="<label for=\"sel_residentType\">Sélectionniez le Type du Résident:</label><select class=\"form-control\" id=\"sel_residentType\"><option value=\"0\" selected=\"\">Type Résident</option>";
var options ="";
$.get("../api/v1/get/menus/typeresident.json.php", function(dataset, status){
for (var index in dataset){
options = options + "<option value=\""+dataset[index].id+"\">"+dataset[index].description+"</option>";
//console.log(options);
}
console.log(options);//Ex1
});
console.log(options);//Ex2
selectElm = selectElm + options + "</select>";
//console.log(selectElm);
//$("#div_sel_residentType").html(selectElm);
}
我想了解为什么它显示console.log(options);//Ex1
但不console.log(options);//Ex2
执行'$ .get'调用后立即执行'Ex2'。呼叫收到响应后执行'Ex1'。 –
'$ .get'是异步的,这意味着当你的响应可用时,你交给它的函数将被调用。与此同时,你的代码已经被执行,来到// Ex2,其中选项仍然是“”。 – connexo