jQuery ajax成功不适用于$(this)?

我一直在使用jQuery中的ajax工具,并且在执行我的ajax成功时遇到了使用$(this)的问题。 我想知道是否有可能在你的成功中使用$(this),因为我见过教程使用它但是当我尝试使用它时它不起作用…但是如果我使用$(文档)或其他方法来获取我希望它的对象工作正常…任何帮助将不胜感激,因为我是jQuery的新手! 提前致谢! 我玩的代码如下:

$(".markRead").click(function() { var cId = $(this).parents("div").parents("div").find("#cId").val(); var field = "IsRead"; $.ajax({ type: "POST", url: "ajax/contract_buttons.php", dataType: "text", data: "contractId=" + cId + "&updateField=" + field, async: false, success: function(response) { //$(this) doesnt recognize the calling object when in the success function... $(this).find("img").attr("src", "images/read.png"); }, error: function(xhr, ajaxOptions, thrownError) { alert(xhr.statusText); alert(thrownError); } }); }); 

this总是指当前的执行上下文,因此它不一定在回调函数中保持相同,如ajax成功处理程序。 如果你想引用它,你必须像Dennis指出的那样,将它的值保存到你自己的局部变量中,这样你以后就可以引用它,即使实际的this值可能已被设置为其他值。 这绝对是javascript的细微差别之一。 将您的代码更改为:

 $(".markRead").click(function() { var cId = $(this).parents("div").parents("div").find("#cId").val(); var field = "IsRead"; var element = this; // save for later use in callback $.ajax({ type: "POST", url: "ajax/contract_buttons.php", dataType: "text", data: "contractId=" + cId + "&updateField=" + field, async: false, success: function(response) { //$(this) doesnt recognize the calling object when in the success function... $(element).find("img").attr("src", "images/read.png"); }, error: function(xhr, ajaxOptions, thrownError) { alert(xhr.statusText); alert(thrownError); } }); });