3

Can someone let me know what is the difference between this and jQuery(this)? I found that my code works if I use 'this' and if I use jQuery(this) it does not work. Does jQuery(this) not query for the current object and return it?

I want to know the index of the image being clicked ( I now we have the index() method, but still want it through the below logic) Here is the full code:(edited as per request)

for(i=0;i<5;i++)
{
jQuery("#div1").append("<img src='slider.jpg'>");
}
imgArr=jQuery("#div1>img");
jQuery("#div1>img").click(display);
function display()
{
  for(i=0;i<imgArr.length;i++)
  {
     if(this==imgArr[i])
     {
      alert(i);
     }
  }
}

Here if I replace this with jQuery(this) it does not work.

codingsplash
  • 4,785
  • 12
  • 51
  • 90
  • check this question http://stackoverflow.com/questions/8719635/jquery-this-versus-this-and-maybe-even-this – Ashish Gupta Jun 27 '12 at 13:42
  • it depends on the context it's in; could you show us more of the code? i.e. the function this is part of? – bokonic Jun 27 '12 at 13:42
  • There is not enough information here to determine what 'this' is... JavaScript scoping is hard enough without seeing it out of context! Have a look here: http://stackoverflow.com/questions/500431/javascript-variable-scope – Simon Jun 27 '12 at 13:43

1 Answers1

5

I suppose "this" is a reference to a DOM element in your first example?

jQuery(this) is actually a jQuery wrapper around one or more DOM elements. So when you compare to a DOM element, it will never be equal.

If you want the DOM element from a jQuery wrapper, use the indexer to get the first element:

jQuery(this)[0] === this
Philippe Leybaert
  • 168,566
  • 31
  • 210
  • 223