-2

I am a bit confused about the usage of this and $(this).

Let's take the following example:

$('a.thmb')click( function() {
  var img_url = $("img",this).attr("src");
  $("#preview_img").attr( "src", img_url);
  $("#preview_img").load( function(){
    var pwidth = this.width;
    var pheight = this.height;
    //alert( $(this).width() ); // 0 <-- (1-1)
    //alert( this.width );     //720 <-- (1-2)
     $.fancybox({
         ....
         onStart: function(){
            //alert( $("#preview_img").width() ); // 0 <-- (2)
         },
         onComplete: function(){
            //alert( $("#preview_img").width() ); //720 <-- (3)
         }
     });
     //alert( $(this).width() ); //720 <-- (4)
  });
}
  1. What is the difference between (1) ?
  2. What is the difference between (2) and (3)?

I want to know question 2. and the reason for difference (1-1) and (4)? just time?

koponyang
  • 1
  • 2

2 Answers2

2

this is a variable that contains a reference to the image element with id "preview_img".

Passing this as an argument to jQuery ( $(this) ) creates a jQuery collection containing that element.

The width property of the image element (this.width) gives you the width property of the image tag.

The jQuery width() method gives you a computed width of the first element in the collection.

nderscore
  • 4,182
  • 22
  • 29
  • Beat me to it... Nice. (And not to mention with more detail.) – Casey Falk Jul 03 '14 at 02:35
  • Could you try making a demo to show the case in which they return different values, here you see in this demo (we don't explicitly set the width via `width` property) they are equal http://jsfiddle.net/GC3kS/1/ – King King Jul 03 '14 at 02:40
1

This is certainly a duplicate, but the gist is that the latter $(this) is JQuery object that calls on the "width" method of the jQuery object, while the former is simply a reference to a DOM element and you are getting the width attribute of that element.

Casey Falk
  • 2,617
  • 1
  • 18
  • 29