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); } });});