Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the jQuery $(this) referring to in this specific code fragment?

Tags:

jquery

$(document).ready(function() {
            $(".po").click(function(){
                var po = $(this).text();
                var dataString = 'po='+ po;

                $.ajax
                    ({
                    type: "GET",
                    url: "projectitems.php",
                    data: dataString,
                    cache: false,
                    success: function(html)
                        {


$(this).closest(".resultsItems").html(html);
                        }
                    });
            });         
        });

The line $(this).closest(".resultsItems").html(html); what exactly is (this) referring to? I'm trying to append the returned ajax result to a <td> called .resultsItems but only to the one below the intial clicked selector? Is this possible?

Just to make it clear i'm not asking what (this) means in jQuery, i'm asking what (this) is referring to in my code above!

like image 474
benhowdle89 Avatar asked Dec 07 '10 16:12

benhowdle89


People also ask

What does $( this mean in jQuery?

$(this) is a jQuery wrapper around that element that enables usage of jQuery methods. jQuery calls the callback using apply() to bind this . Calling jQuery a second time (which is a mistake) on the result of $(this) returns an new jQuery object based on the same selector as the first one.

What is $( this in JavaScript?

$(this) is a jQuery object and this is a pure DOM Element object. See this example: $(".test"). click(function(){ alert($(this). text()); //and alert(this.

What is difference between $( this and this in jQuery?

Difference between this and $(this)The this Keyword is a reference to DOM elements of invocation. We can call all DOM methods on it. $() is a jQuery constructor and in $(this), we are just passing this as a parameter so that we can use the jQuery function and methods.

When we should use $( this in jQuery?

this would refer to the current DOM element h1 which invoked the event. Enclosing it with a $ makes it a jquery object. So $(this) basically refers to the jquery h1 object . So $(this) = $('h1') where h1 is the event which triggered the event.


1 Answers

this refers to the $.ajax() settings object. To get what you want, you'll need to maintain this by using the context option like this:

$.ajax({
  context: this,
  type: "GET",
  url: "projectitems.php",
  data: dataString,
  cache: false,
  success: function(html) {
    $(this).closest(".resultsItems").html(html);
  }
});
like image 122
Nick Craver Avatar answered Oct 03 '22 21:10

Nick Craver