从调用$ .getJSON外界物体 [英] Calling external objects from $.getJSON
问题描述
可能重复:
<一href="http://stackoverflow.com/questions/3323189/why-doesnt-this-closure-have-access-to-the-this-keyword-jquery">Why没有这个封闭有机会获得'这个'关键字? - jQuery的
函数Class1的(){
this.url = 'http://en.wikiquote.org/w/api.php?action=query&format=json&prop=revisions&titles=Albert_Einstein&rvprop=content&callback=?';
this.f =功能(){
$ .getJSON(this.url,函数(){
执行console.log(this.url);
});
}
};
VAR OBJ =新1级();
obj.f();
除了打印网址的
, obj.f()
打印不确定到控制台。为什么会出现这种情况,我能做些什么,以prevent这种行为?
在你的Ajax回调,这
将是jqXhr对象,而不是你的当前对象。你要保存这
在你的Ajax调用和参考价值的是的在回调:
this.f =功能(){
无功自我=这一点;
$ .getJSON(this.url,函数(){
执行console.log(self.url);
});
}
Possible Duplicate:
Why doesn't this closure have access to the 'this' keyword? - jQuery
function class1() {
this.url = 'http://en.wikiquote.org/w/api.php?action=query&format=json&prop=revisions&titles=Albert_Einstein&rvprop=content&callback=?';
this.f = function() {
$.getJSON(this.url, function() {
console.log(this.url);
});
}
};
var obj = new class1();
obj.f();
Instead of printing the url, obj.f()
prints "undefined" to the console. Why is this happening and what can I do to prevent this behaviour?
Inside your ajax callback, this
will be the jqXhr object, not your current object. You'll want to save the value of this
before your ajax call, and reference that in your callback:
this.f = function() {
var self = this;
$.getJSON(this.url, function() {
console.log(self.url);
});
}
这篇关于从调用$ .getJSON外界物体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!