SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Evangelist
    Join Date
    Nov 2009
    Posts
    471
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    using $(this) in a callback function

    I have created a click event handler on an anchor and can reference it using $(this) just fine until I include a $.post function which processes the return data using a callback function. Once in the callback function, the $(this) no longer works.

    How can I refer to the clicked anchor from within the $.post callback function? After way too long trying different combinations of things and making it work and break, I am first of all assuming that is what is going on, i.e. that once I am in the callback function, I no longer have access to $(this).

    Anyhow, any advice would be welcome at this point.

    Thanks

  2. #2
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,192
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Before your $.post callback add

    Code JavaScript:
    var thisname = $(this);

    You can name it anything but a javascript predefined reserved word, then when you want to call $(this) just replace that with for exmaple

    Code JavaScript:
    thisname.css();

  3. #3
    SitePoint Evangelist
    Join Date
    Nov 2009
    Posts
    471
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Brilliant. Thank you, thank you, thank you. Funny, I almost tried that but at 1:30 in the morning my inquisitiveness was about tapped out. Just tried it now and it works like a champ. Have a great day.

  4. #4
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,192
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Your welcome

  5. #5
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,151
    Mentioned
    16 Post(s)
    Tagged
    3 Thread(s)
    An inline function can also be used to bind a reference rather than populating the outer function with unnecessary variables.

    Code JAVASCRIPT:
    $.ajax({	
    	url: '--'
    	,success:(function(me) {
    		return function(data,status,xhr) {
    			alert(me);
    		};
    	})(this)
    });


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •