How to know the target element that raised the event in the ajax response callback?
I am posting to the server using jquery ajax using $.post. After server returns the response, I process the response in the callback function. In this callback function, how can I know which element was clicked on. Please check the following. In the function handleServerResponse, I would like to know the DOM element that raised this event. Precise I want to access the $(this) element availabl开发者_如何学运维e in handleFavouritesUI function. I am using jquery with ASP.NET MVC.
<script type="text/javascript">
$(function() {
$("a.favourite-on, a.favourite-off").click(handleFavouritesUI);
});
function handleFavouritesUI(e) {
var link = $(this).attr("href");
$.post(link, handleServerResponse);
e.preventDefault();
return false;
}
function handleServerResponse(data, textStatus) {
response = eval(data);
var targetElement = null;
// TODO: get the target element.
if (!response.success) {
showMessage(targetElement, response.reason, true);
}
else {
//TODO: Modify the target element.
}
}
</script>
Change the handleServerResponse to an inline function...
function handleFavouritesUI(e) {
var link = $(this).attr("href");
$.post(link, function(data,textStatus){
var targetElement = null;
if (!response.success) {
showMessage(targetElement, response.reason, true);
}
else {
// See, the link object still holds the same reference.
link.fadeOut().fadeIn();
}
});
e.preventDefault();
return false;
}
Read up a bit on closures in JavaScript to better understand how this works.
精彩评论