我需要从jQuery JSON调用访问一个外部本地变量,而不将该变量发送到服务器(因此不使用data参数):
for (var prop in channels) {
$.getJSON(url).done(function(json) {
channels[prop].value = ...;
});
}
不幸的是,随着外部循环的继续,prop
变量会发生变化。
是否可以将变量绑定到getJSON调用?
发布于 2013-05-06 18:52:38
好了,找到了基于jQuery's proxy function的答案
for (var prop in channels) {
$.getJSON(url).done(
$.proxy(function(json) {
channels[this._prop].value = ...;
}, {_prop: prop}
);
}
本质上,$.proxy()
创建了一个包装器函数,该函数接受附加的context
参数,并确保将其作为this
传递给包装函数。
发布于 2017-06-28 21:58:52
与js :bind一起使用:
for (var prop in channels) {
$.getJSON(url).done(function(json) {
channels[this].value = ...;
}.bind(prop));
}
$.ajax context的用法:
for (var prop in channels) {
$.ajax({
url: url,
dataType: 'json',
context: param,
success: function(data) {
channels[this].value = ...;}
})
}
https://stackoverflow.com/questions/16396260
复制相似问题