【发布时间】:2010-10-12 19:19:59
【问题描述】:
我通过将标签字符串保存到变量中来缓存它们,但遇到了奇怪的范围问题。我知道这与闭包有关,但我似乎无法弄清楚到底是什么问题。
info_lbl = {};
$("#chkCorporateGift").click(function(){
var type = $(this).is(":checked") ? "Corporate" : "Personal";
if(!info_lbl.hasOwnProperty(type)){
$.ajax({
url: svc_og + "Get" + type + "InformationLabel",
success: function(data){
info_lbl[type] = data;
}
});
}
$("#lblInformationType").text(info_lbl[type]);
});
第一次调用 GetCorporateInformationLabel 或 GetPersonalInformationLabel 方法时未设置 lblInformationType 标签。在第一次调用每个标签后,标签的值正在更改。有人可以解释为什么会发生这种行为吗?当我使用 Firebug 并在 $("#lblInformationType").text(info_lbl[type]); 上设置断点时,info_lbl[type] 包含正确的值,并且在前两个调用中一切正常。
【问题讨论】:
标签: javascript jquery ajax closures