Sorry for the question title, I know it's not very well worded, but I couldn't really explain what I'm asking in a summary.
I have a JQuery function tied to the click event of an element. For reasons that may well be flawed (other than making more sense to me personally), within this function I am calling another function. From the second function, I'd like to be able to call $(this)
from the first function, but I'm not sure if it's possible, or how to do it if I can
Example
JQuery function which works
$('.member-div a').on("click",function(f){
f.preventDefault();
var x = $(this).parent('div').attr('id').slice(-1);
$('.member-div').hide();
if($(this).hasClass('next')){
var y = parseInt(x)+1;
};
if($(this).hasClass('back')){
var y = parseInt(x)-1;
};
$('#section'+y).show();
});
What I'm trying to do
$('.member-div a').on("click",function(f){
f.preventDefault();
newfunc();
});
function newfunc(){
var x = $(this).parent('div').attr('id').slice(-1);
$('.member-div').hide();
if($(this).hasClass('next')){
var y = parseInt(x)+1;
};
if($(this).hasClass('back')){
var y = parseInt(x)-1;
};
$('#section'+y).show();
};
I think I understand why the second way doesn't work ($(this)
will not be the anchor tag from the initial function), but I am lost as to how to make it work
If I have to, or if anyone can explain that/why it is better to, I will stick with the original example that works!
Thanks
Always be careful when using the
this
as you may end up using an unexpected value depending on the context your function was called.Instead, you should consider using a parameter: