function Tour(el) {
var tour = this;
this.el = el;
this.fetchPhotos = function() {
$.ajax('/photos.html', {
data: {location: tour.el.data('location')},
context: tour,
success: function(response) {
console.log(this===tour);
this.el.find('.photos').html(response).fadeIn();
},
error: function() {
this.el.find('.photos').html('<li>There was a problem fetching the latest photos. Please try again.</li>');
},
timeout: 3000,
beforeSend: function() {
this.el.addClass('is-fetching');
},
complete: function() {
this.el.removeClass('is-fetching');
}
});
}
this.el.on('click', 'button', this.fetchPhotos);
}
$(document).ready(function() {
var paris = new Tour($('#paris'));
var london = new Tour($('#london '));
});
控制台日志输出成功功能= true
上面的代码片段来自教程。我有2个与此相关的查询&#39;对象
&#39;游&#39; &安培; &#39;这&#39;是相同的(如输出所示),但当我更换&#39; tour&#39;用这个&#39;在ajax调用的数据选项中,它停止工作。为什么会这样?
为什么我们不使用&#39; tour&#39;在其他函数内部 - error,beforeSend.etc。
请有人帮忙。
答案 0 :(得分:1)
这一切都与Ajax调用中的“context”关键字有关。 Context告诉它在调用其中一个Ajax回调(例如成功)时会出现什么“this”。在你的情况下,你将'tour'作为上下文传递,这意味着在你的成功函数中,'this'等于'tour'。