我试图更改一些使用onclick的旧代码,以便我使用$(this).问题是$(this)在成功的时候不起作用.反正有没有把它设置为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");
}
}
});
});
Run Code Online (Sandbox Code Playgroud)
Fel*_*ing 217
在回调内部,this引用jqXHRAjax调用的对象,而不是事件处理程序绑定的元素.详细了解thisJavaScript的工作原理.
如果你可以使用ES2015 +,那么使用箭头功能可能是最简单的选择:
$.ajax({
//...
success: (json) => {
// `this` refers to whatever `this` refers to outside the function
}
});
Run Code Online (Sandbox Code Playgroud)
您可以设置context选项:
此对象将成为所有与Ajax相关的回调的上下文.默认情况下,上下文是一个对象,表示调用中使用的ajax设置(
$.ajaxSettings与传递给的设置合并$.ajax).(......)
$.ajax({
//...
context: this,
success: function(json) {
// `this` refers to the value of `context`
}
});
Run Code Online (Sandbox Code Playgroud)
或使用$.proxy:
$.ajax({
//...
success: $.proxy(function(json) {
// `this` refers to the second argument of `$.proxy`
}, this)
});
Run Code Online (Sandbox Code Playgroud)
或者保持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
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
48755 次 |
| 最近记录: |