AJAX成功内部的$(这个)不起作用我正在尝试更改一些使用onClick的旧代码,这样我就可以使用$(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");
}
}
});});
2 回答
料青山看我应如是
TA贡献1772条经验 获得超8个赞
问题
thisjqXHRthis
解
$.ajax({
//...
success: (json) => {
// `this` refers to whatever `this` refers to outside the function
}});context
这个对象将成为所有与Ajax相关的回调的上下文。默认情况下,上下文是一个对象,它表示调用中使用的Ajax设置( $.ajaxSettings与传递给 $.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
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
}});相关
弑天下
TA贡献1818条经验 获得超8个赞
jQuery(".custom-filter-options .sbHolder ul li a").each(function () {
var myStr = jQuery(this).text();
var myArr = myStr.split(" (");
url = 'your url'; // New Code
data = myArr[0];
try {
jQuery.ajax({
url : url,
context: this,
type : 'post',
data : data,
success : function(data) {
if(data){
jQuery(this).html(data);
}else{
jQuery(this).html(myArr[0]);
}
}
});
} catch (e) {
} });添加回答
举报
0/150
提交
取消
