How come $(this) is undefined after ajax call

前端 未结 5 1781
无人共我
无人共我 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:21

    You should try

    $('.commentDeleteLink').live('click', function(event) {
        event.preventDefault();
        var result = confirm('Proceed?');
        var that = this;
        if ( result ) {
            $.ajax({
                url: window.config.AJAX_REQUEST,
                type: "POST",
                data: { action       : 'DELCOMMENT',
                        comment      : $('#commentText').val(),
                        comment_id   : $(this).attr('href') },
                success: function(result) {
                    alert($(that).attr('href'));
                    //$(that).fadeOut(slow);
                }
            });
        }
    });
    

    because this in the callback is not the clicked element, you should cache this in a variable that that you can re-use and is not sensible to the context

提交回复
热议问题