Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
524 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...