Reputation: 7688
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');
Upvotes: 3
Views: 699
Reputation: 339826
You can only declare var foo
when 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.
Upvotes: 4
Reputation: 87073
$('some').on('click', function() {
var refrence = $(this);
var span = refrence.find('span')
// to override the $this you can use
refrence = refrence.find('span');
});
Upvotes: 2
Reputation: 754763
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.
Upvotes: 3