可能重复:
AJAX 成功中的 $(this) 不起作用
我正在使用一个按钮单击,其中有一个 ajax 回调。如果它返回成功,我想向我的按钮添加一个类,$(this).addClass('abc');
但没有用。
$(this)
不在 AJAX 中工作。这样做的替代方法是什么,因为有几个相同的块。
可能重复:
AJAX 成功中的 $(this) 不起作用
我正在使用一个按钮单击,其中有一个 ajax 回调。如果它返回成功,我想向我的按钮添加一个类,$(this).addClass('abc');
但没有用。
$(this)
不在 AJAX 中工作。这样做的替代方法是什么,因为有几个相同的块。
一旦你在 AJAX 回调内部,this
就不再指向你的按钮(谷歌“JavaScript 闭包和这个”以获得更多信息)。
您需要将对当前的引用保存this
到一个变量中,然后使用它来添加类。像这样的东西:
$( '#button' ).click ( function () {
var $this = $( this );
$.get (
'url',
function ( data ) {
$this.addClass ( 'abc' );
}
);
} );
你是对的。this 在 ajax 调用中不可访问,因为它是对 ajax 对象的引用。但是,您可以将其保存为另一个变量并在回调中使用它。
工作演示:http: //jsfiddle.net/gZ8qB/
$("#mybutton").click(function () {
var $this = $(this);
$.ajax({
url: "http://fiddle.jshell.net/favicon.png",
beforeSend: function ( xhr ) {
xhr.overrideMimeType("text/plain; charset=x-user-defined");
}
}).done(function ( data ) {
$this.addClass("done");
});
});
保存$(this)
到变量..并使用它
试试这个
var $this=$(this);
进行ajax调用..并使用
$this.addClass("done");
该$(this)
对象未在 AJAX 调用的回调函数中定义。如果需要引用触发调用的原始元素,可以将其分配给事件处理函数中的变量,使其在回调函数范围内也可用。
例如(使用$.get
简写):
$('#some-button').on('click', function() {
var some_button = $(this); // Assign the variable in the event handler
$.get('some_url',{some_ariable:'some_value'}, function(data) {
some_button.addClass('some_class'); // some_button is now also in the scope of the AJAX callback function
});
});
这个概念被称为closures
,其中"functions have access to variables that were available in the scope where the function was created"
。有关此主题的更多信息,请参见jQuery's - Javascript 101。