lambda 函数中未定义的变量

variable undefined in lambda function

我有这个代码:

$.post("call.php", {form: data.item.value, positiony: t}, function (data){ top[t] = data;});
$("#pos" + t).css("margin-top", top[t] );

我用 ajax 的函数 post 调用一个页面,返回值用于设置一系列 div 的边距顶部,增量 ID #pos0,#位置 1...; 如果我将 t 更改为 n 次,其中 n 是 div 的数量,我没有问题;但是如果我使用 'for' 来增加值,我在 lambda 函数中有未定义的变量 t ;事实上,如果我在 lambda 函数之后打印 top[t],打印的值是未定义的。 我该如何解决?

Ajax 是 异步的 。您的第二行是 运行 before ajax 调用完成。将它 移到 成功处理程序中:

$.post("call.php", {form: data.item.value, positiony: t}, function (data){
    top[t] = data;
    $("#pos" + t).css("margin-top", top[t] );
});

此外,如果您使用 t 作为计数器在循环中执行此操作,请注意您所有的成功函数都将持久引用 t 变量,不是创建时的副本。所以你可能想要一个构建器函数,或者只是 Function#bind:

for (t = something; t < somethingElse; ++t) {
    $.post("call.php", {form: data.item.value, positiony: t}, function (tValue, data){
        top[tValue] = data;
        $("#pos" + tValue).css("margin-top", top[tValue] );
    }.bind(null, t));
}