Search code examples
jquerybindthislive

Maintain reference to this in jQuery


I'm converting a bunch of hyperlinks to make simple GET requests using jQuery. I want to maintain the reference to this within the Ajax call, do i need to be using bind/live/something else?

$(document).ready(function(){
    $(".mylink").click(function(){
        var url = $(this).attr('href');
        $.get(url,function(data){
            $(this).parent().html(data); // this is now out of scope
        });
        return false;
    });
});

Solution

  • $(document).ready(function(){
        $(".moderate").click(function(){
            var $this = $(this);
            var url = $this.attr('href');
    
            $.get(url,function(data){
                $this.parent().html(data);
            });
            return false;
        });
    });
    

    That should work for you.