Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery re-declare $(this)

Is it not possible to re-declare $.(this) after a $.click() function? because none of these seems to work:

$(this) = $(this).find('span');
var $(this) = $(this).find('span');
like image 588
Alex Avatar asked Dec 02 '25 05:12

Alex


2 Answers

You can only declare var foowhen foo is a legal identifier.

$(this) is the result of calling the function named $ with argument this so it isn't legal in a declaration.

Nor should you overwrite this - it will cause much head scratching in the future!

If you want a local variable for storing the jQuery version of this then a common convention is:

var $this = $(this);
var $span = $this.find('span');

where the (perfectly legal, but sometimes frowned upon) $ prefix allows you to remember that the variable is a jQuery object, and not a plain DOM element.

That convention also allows you to spot the wasteful (but common) error of doing:

var jqobj = $(myobj)

when myobj is already a jQuery object.

like image 50
Alnitak Avatar answered Dec 03 '25 19:12

Alnitak


The expression $(this) is not a variable declaration but instead is an expression. If you want to redeclare something you need to store it in a variable

var saved = $(this);
saved = $(this).find('span');

The reason the final version works is because you are assigning it to an actual identifier.

like image 29
JaredPar Avatar answered Dec 03 '25 18:12

JaredPar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!