나는 $ (this)를 사용하도록 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");
}
}
});
});
답변
문제
콜백 내에서 이벤트 핸들러가 바인딩 된 요소가 아니라 Ajax 호출 this
의 jqXHR
객체를 참조 합니다. JavaScript에서 작동 하는 방법에 대해 자세히 알아보십시오this
.
솔루션
ES2015 +를 사용할 수있는 경우 화살표 기능 을 사용하는 것이 가장 간단한 옵션 일 것입니다.
$.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
}
});
관련
답변
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) {
}
});