Reputation: 45
Given the code:
$(element, document).mousedown(function() {
$(this).attr('id'); // get id of the element
});
how to rewrite the code without using this
?
Upvotes: 3
Views: 334
Reputation: 1400
You can use the following:
$(element, document).mousedown(function(e) {
$(e.target).attr('id'); // Get id of the element.
});
Upvotes: 1
Reputation: 81988
The problem is that you're not going to get anything more efficient than use of this
. Everything else will more or less require a second element lookup which, while not deathly expensive is nevertheless more costly than using the object in scope (this
).
Strictly speaking, this is the most literal interpretation:
$(element, document).mousedown(function() {
$(element, document).attr('id');
});
Now, this might be OK, but if your element is actually a selector which returns multiple values (like a class selector), you'll have problems. So, instead, you might want to consider:
$(element, document).each( function( ind, elem ) {
elem.mousedown( function(){ elem.attr( 'id' ); } );
} );
Upvotes: 0
Reputation: 21762
"this" refers to the scope of the function. With regards to the function, This is the element being acted upon. In the case of you code, the action is mousedown, so the element being acted upon is this. Hope this help.
Upvotes: 0
Reputation: 4868
In this case "this" is refering to the element that is being clicked. It's not required but you'll have to have code like this for every element:
$("#button").mousedown(function(){
$("#button").attr("id");
})
It's much easier to leave it in
Upvotes: 0
Reputation: 23648
this in JavaScript stands for the execution context of a function. In this case you benefit from jQuery setting this
to the element you bound things on. But with self-written functions you'll usually end up with this referring to the global object.
In case you ever enter a new function scope you usually have to preserve this because a new function has a new this.
For example
$('div').each(function(index, item) {
var that = this;
$(this).mousedown(function() {
//this could be something different than before
//so we use the that reference
$(that).hide();
}
});
Upvotes: 0
Reputation: 449385
what is THIS stands for?
In this context, this
points to the element that you are currently defining the mousedown
property for.
I can't see a reason not to use it here. Can you elaborate on what you want to do?
Upvotes: 3
Reputation: 5579
A version without the this
keyword:
var $element = $('#element');
$element.mousedown(function() {
var id = $element.attr('id');
// id is now 'element'
});
Upvotes: 1