Reputation: 10555
I'm using same element in multiple functions like below:
$('.edit').on('click',function(){
var elem1 = $(this).closest('tr').find('td').eq(0);
var elem2 = $(this).closest('tr').find('td').eq(1);
console.log(elem1);
});
$('.update').on('click',function(){
var elem1 = $(this).closest('tr').find('td').eq(0);
var elem2 = $(this).closest('tr').find('td').eq(1);
console.log(elem1);
});
So, I want to sort my variable outside the function so that they can be referenced in multiple functions like below:
var elem1 = $(this).closest('tr').find('td').eq(0);
var elem2 = $(this).closest('tr').find('td').eq(1);
$('.edit').on('click',function(){
console.log(elem1);
});
$('.update').on('click',function(){
console.log(elem1);
});
But $(this)
doesn't refer to the current function context. So, how should I manage?
Upvotes: 0
Views: 115
Reputation: 13858
this
refers to the scope where the method/function is called. So in your example code, this
is actually global scope (window
in browser).
You could pass this
as an argument.
var elem1 = function(ref) {
return $(ref).closest('tr').find('td').eq(0)
};
var elem2 = function(ref) {
return $(ref).closest('tr').find('td').eq(1);
}
$('.edit').on('click',function(){
console.log(elem1(this));
});
$('.update').on('click',function(){
console.log(elem1(this));
});
Upvotes: 2