How come $(this) is undefined after ajax call

前端 未结 5 1787
无人共我
无人共我 2020-12-21 15:38

I am doing an ajax request when an anchor tag is clicked with an ID set to href. Btw, this anchor tag is dynamically created.



        
5条回答
  •  醉酒成梦
    2020-12-21 16:07

    The context of the click event handler (the object that this refers to in that handler) is not propagated to your AJAX success callback.

    You can capture the value of this from the caller by assign it to a local variable, or you can explicitly propagate it by passing this in the context option to $.ajax():

    $.ajax({
        url: window.config.AJAX_REQUEST,
        type: "POST",
        data: {
            action: "DELCOMMENT",
            comment: $("#commentText").val(),
            comment_id: $(this).attr("href")
        },
        context: this,
        success: function(result) {
            $(this).fadeOut("slow");  // Works, since 'this' was propagated here.
        }
    });
    

提交回复
热议问题