Sto cercando di modificare un vecchio codice che utilizza onclick in modo che io possa usare $ (questo). Il problema è che $ (questo) non funziona quando si trova all’interno del successo. C’è comunque da fare senza impostarlo come 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"); } } }); });
All’interno del callback, this
riferisce all’object jqXHR
della chiamata Ajax, non all’elemento al quale è stato associato il gestore eventi. Ulteriori informazioni su come funziona in JavaScript .
Se ES2015 + è disponibile per te, quindi usare una funzione a freccia potrebbe essere l’opzione più semplice:
$.ajax({ //... success: (json) => { // `this` refers to whatever `this` refers to outside the function } });
È ansible impostare l’ opzione di context
:
Questo object sarà reso il contesto di tutti i callback relativi ad Ajax. Per impostazione predefinita, il contesto è un object che rappresenta le impostazioni ajax utilizzate nella chiamata (
$.ajaxSettings
unite con le impostazioni passate a$.ajax
). (…)
$.ajax({ //... context: this, success: function(json) { // `this` refers to the value of `context` } });
o usa $.proxy
:
$.ajax({ //... success: $.proxy(function(json) { // `this` refers to the second argument of `$.proxy` }, this) });
o mantenere un riferimento al valore di this
al di fuori del 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 } });
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) { } });