$(this) 内部 AJAX 成功不起作用 [英] $(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`回调?
这篇关于$(this) 内部 AJAX 成功不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!