在for循环中利用闭包实现ajax同步
在项目中 出现需要通过修改多个HTML元素内容的情况使用
var displaySquare=$(".displaySquare");
for(var i =0;i< displaySquare.length;i++){
var id = displaySquare[i].getAttribute("data-id");
(function(i){
$.ajax({
type: "post",
url: url,
data: {deviceId: id},
timeout: 5000,
async:false,
success: function(data){
if(data){
$("#"+id).html(data);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown){
//请求出错处理
}
});
})(i)
};
以上 ,在使用闭包之后,可以确保每一个元素都能正确赋值