Is jquery $(this). the same as $?
This question already has an answer here:
It is a very typical convention where a developer will prefix a variable name with $
to indicate it is a jQuery object, and will have access to all the typical jQuery methods. It is not a selector.
In your example you have this: var $parent = $(this).parent();
. This is a reference to the DOM object, once you have saved that, you can use it multiple times:
You can do this:
$(this).parent().css('color', 'green');
$(this).parent().css('border', '1px solid pink');
$(this).parent().css('background', 'purple');
In this example, jQuery will select the $(this)
object, and then select its parent
You can also do this:
var $parent = $(this).parent();
$parent.css('color', 'green');
$parent.css('border', '1px solid pink');
$parent.css('background', 'purple');
You have saved the reference to the parent, and made jQuery only look it up once.
*Small sidenote: The css method can be done better, I did it this way for demo-purposes *
$parent
is a variable name. It has nothing to do with the jQuery library.
Many developers use the $
prefix for variables to identify them as jQuery collections.
The dotted functions (ie $.post
and $.each
) are simply indicative that they're part of the jQuery library, for example (and I hasten to add this isn't how jQuery is written!):
var $ = {
post: function() { },
each: function() { }
}
In the above example, we can now access the two functions as $.post()
and $.each()
respectively.
When you use $(this)
, you're taking the current HTML Object, and generating a jQuery object so that you can use the added functions that jQuery brings to the table. For example:
this.style.color = '#000';
Is identical to doing something like:
$(this).css('color', '#000');
$
before a variable is just a convention. A lot of people us it to describe a variable which is a jQuery object. It doesn't actually do anything special. You could prefix all of your javascript variables with it if you wanted to (not sure why you would, but it would be valid).
It's similar to the convention many devs use to denote that a variable/method should be private ( _privateVar
).
上一篇: 区别var foo和var $ foo