问题
在回调内部,this指的是jqXHR对象,而不是事件处理程序绑定到的元素。了解更多关于如何this在JavaScript中工作.
解
如果ES 2015+对您可用,则使用箭头函数可能是最简单的选择:$.ajax({
//...
success: (json) => {
// `this` refers to whatever `this` refers to outside the function
}});这个对象将成为所有与Ajax相关的回调的上下文。默认情况下,上下文是一个对象,它表示调用中使用的Ajax设置($.ajaxSettings与传递给$.ajax). (...)$.ajax({
//...
context: this,
success: function(json) {
// `this` refers to the value of `context`
}});$.ajax({
//...
success: $.proxy(function(json) {
// `this` refers to the second argument of `$.proxy`
}, this)});
的值的引用。this在回调之外:var element = this;$.ajax({
//...
success: function(json) {
// `this` refers to the jQXHR object
// use `element` to refer to the DOM element
// or `$(element)` to refer to the jQuery object
}});
相关