“context : this”と設定するとコールバック関数内で$(this)を使えるようになる。
jQuery
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
$('.hoge').on('click', function() { $.ajax({ type:'POST', url:'https://example.com/hoge', dataType: 'json', context : this, // これでコールバック関数内で$('hoge')を$(this)として使える }).done(function (result){ // 成功時 }).fail(function(jqXHR, textStatus, errorThrown){ // 失敗時 }); }); |
公式ドキュメントを見るとDOMを渡せるらしく、thisだけではなくdocument.bodyなども渡せる(渡したものがコールバック関数内での$(this)となる)。
公式ドキュメントのサンプル
1 2 3 4 5 6 7 8 |
$.ajax({ url: "test.html", context: document.body }).done(function() { $( this ).addClass( "done" ); // <body class="done"></body>になる }); |
jQuery.ajax() | jQuery API Documentation
コメントを残す