So, here is the question
I can not undestand when i should use "this" instead class or id
If u can show example - it will be fantastic
Thanks
So, here is the question
I can not undestand when i should use "this" instead class or id
If u can show example - it will be fantastic
Thanks
I can not undestand when i should use "this" instead class or id
Usually, you do that when you want to refer to the element on which an event was triggered from within the event handler:
$(".foo").on("click", function() {
var $el = $(this); // `this` is the element that was clicked,
// so `$(this)` gives you a jQuery wrapper
// around just that one element.
// But $(".foo") would give you a wrapper
// around **all** .foo elements, not just the
// one that was clicked.
// ...
});
Live Example:
$(".foo").on("click", function() {
var $el = $(this); // `this` is the element that was clicked
$el.text("You've clicked this one");
});
<div class="foo">Not clicked yet</div>
<div class="foo">Not clicked yet</div>
<div class="foo">Not clicked yet</div>
<div class="foo">Not clicked yet</div>
<div class="foo">Not clicked yet</div>
<div class="foo">Not clicked yet</div>
<div class="foo">Not clicked yet</div>
<div class="foo">Not clicked yet</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Sometimes, it comes up when using either each
or $.each
, because jQuery calls the callback to each of those methods with this
referring to the element for that call:
$(".foo").each(function() {
var $el = $(this); // `this` is the element for this callback
// ...
});
The jQuery API documentation will tell you when it's going to set this
to a specific value in a callback.