Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
549 views
in Technique[技术] by (71.8m points)

javascript - jQuery ajax success doesn't work with $(this)?

Ive been playing with the ajax tools in jQuery and am having an issue with using $(this) inside the success of the execution of my ajax. I was wondering if its possible to use $(this) inside of your success as ive seen tutorials use it but when i attempt to use it it doesnt work... However if i use $(document) or some other method to get to the object i want it works fine... Any help would be greatly appreciated as i am quite new to jQuery! Thanks in advance! The code im playing with is as follows:

$(".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);
        }
    });
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

this always refers to the current execution context so it does not necessarily stay the same in a callback function like an ajax success handler. If you want to reference it, you must just do as Dennis has pointed out and save its value into your own local variable so you can reference it later, even when the actual this value may have been set to something else. This is definitely one of javascript's nuances. Change your code to this:

$(".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);
        }
    });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...