I’d like to store some arbitrary data on an element for use in an ajax callback like so:
$(this).data('my_data', 'hey there');
$(this).click(function(e) {
e.preventDefault();
// $(this).data('my_data') == 'hey there' :-)
$.post($(this).attr('href'), '...', function(response) {
// $(this).data('my_data') == undefined :-(
});
});
But in the callback ‘my_data’ is undefined. Am I just doing something wrong or will this not work? What is the best way to go about this?
Thanks.
thisin the context of thepostcallback function isn’t the same this as in the context of theclickcallback.I’d solve that problem by creating a closure:
The closure magic expands the scope of the local variable
thatinto this callback function. This is a bit tricky but useful; have a google on closures in JS for many excellent explanations.