AJAX成功内的$(this)无法正常工作 [英] $(this) inside of AJAX success not working
问题描述
我试图更改一些使用onclick的旧代码,以便我使用$(this).问题是,在成功内部时,$(this)不起作用.无论如何,无需将其设置为var即可执行此操作.
I am trying to change some old code which uses onclick so that I an use the $(this). The problem is that $(this) is not working when inside the success. Is there anyway to do this without setting it as a var.
$('.addToCart').click(function() {
$.ajax({
url: 'cart/update',
type: 'post',
data: 'product_id=' + $(this).attr("data-id"),
dataType: 'json',
success: function(json) {
if (json['success']) {
$(this).addClass("test");
}
}
});
});
推荐答案
问题
在回调内部,this
引用Ajax调用的jqXHR
对象,而不是事件处理程序绑定到的元素. 了解有关this
如何在JavaScript中工作的更多信息.
Problem
Inside the callback, this
refers to the jqXHR
object of the Ajax call, not the element the event handler was bound to. Learn more about how this
works in JavaScript.
如果您可以使用ES2015 +,则使用箭头功能可能是最简单的选择:
If ES2015+ is available to you, then using an arrow function would probably be the simplest option:
$.ajax({
//...
success: (json) => {
// `this` refers to whatever `this` refers to outside the function
}
});
您可以设置 context
选项:
You can set the context
option:
该对象将成为所有与Ajax相关的回调的上下文.默认情况下,上下文是一个对象,代表调用中使用的ajax设置(
$.ajaxSettings
与传递给$.ajax
的设置合并). (...)
This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call (
$.ajaxSettings
merged with the settings passed to$.ajax
). (...)
$.ajax({
//...
context: this,
success: function(json) {
// `this` refers to the value of `context`
}
});
或使用> $.proxy
:
$.ajax({
//...
success: $.proxy(function(json) {
// `this` refers to the second argument of `$.proxy`
}, this)
});
或在回调之外保留对this
值的引用:
or keep a reference to the value of this
outside the callback:
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
}
});
相关
- 如何在内部访问正确的`this`回调?
- How to access the correct `this` inside a callback?
Related
这篇关于AJAX成功内的$(this)无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!