jQuery: Why prepend a $ to variable name?
I am trying to learn jQuery and I came across this line in an example.
var $title = $(tag).attr('title');
Can someone please tell me what the prepended $ is for in $title
.
The example seems to work fine if I replace $title
with just title
.
I understand this is probably a stupid question but it is a waste of time googling for "purpose of $"
Ma开发者_如何学编程ny thanks.
It doesn't "mean" anything. The $
character is a legal character in Javascript variable names.
However, there is a convention (which isn't universal) of using $
as a prefix to any variable that points to a jQuery selection.
You give the example:
var $title = $(tag).attr('title');
This is a bad use of the $
character, according to this convention. $title
is a string, not a jQuery selection.
This would be a correct use of the character:
var $el = $(tag);
var title = $el.attr('title');
Otherwise, a big reason for the prevalence of the $
character is that it is mandatory in PHP, and there is a big overlap between jQuery and PHP programmers.
I think people use it as a convention for 'things I looked up with jQuery that I want to hold onto without needing to look up again'.
The one you see most often is var $this = $(this)
$ is a valid character in javascript variable names. It makes no difference in the snipped you posted. See this related answer.
Looks like a PHP developer was getting a bit tired and didn't realise he was in a javaScript code block.
In JavaScript you don't need to have $ on variable names. However, to access the element using jQuery (usually by the $) you'll need the $ on the ('#selector_id')
bit - i.e. $('#selector_id')
.
The intent of this is to denote to the programmer that the variable is a jQuery wrapper object.
In javascript $
is nothing. This is the same as add a
to title (atitle
). It's just a symbol you can use for names.
there is no purpose for $, it's just named that way. =)
The symbol '$' is mapped to the jQuery class. There is NO reason to prefix title with '$'.
精彩评论