Reputation: 493
In JQuery, it seems that $(this) only works locally.
give a quick example:
$(".someClass .type1").click(function(){
$(".someClass .type1").html("<img src='image/2.png'>");
$(this).html("<img src='images/img.png'>");
});
$(".otherClasses").click(function(){
$(".otherClasses .type1").html("<img src='image/2.png'>");
$(this).html("<img src='images/img.png'>");
});
Ideally, I want to write a function like this:
function changeImg () {
$(this).html("<img src='images/img.png'>");
}
And then call changeImg() under the jquery click functions like:
$(".someClass .type1").click(function(){
$(".someClass .type1").html("<img src='image/2.png'>");
changeImg();
});
However, in this way, the $(this) will be 'undefined' instead of the one that is clicked anymore. Is there a way to make it available like a global variable?
Thank you!
Upvotes: 0
Views: 44
Reputation: 27012
You could do this to set the context:
changeImg.call(this);
See MDN for Function.prototype.call
Upvotes: 3
Reputation: 57095
Use
changeImg(this); // pass this here
you code becomes
$(".someClass .type1").click(function(){
$(".someClass .type1").html("<img src='image/2.png'>");
changeImg(this); // pass this here
});
function changeImg (elem) {
$(elem).html("<img src='images/img.png'>");
}
Upvotes: 1
Reputation: 3517
Pass this
as a parameter to your functions:
function changeImg (el) {
$(el).html("<img src='images/img.png'>");
}
$(".someClass .type1").click(function(){
$(".someClass .type1").html("<img src='image/2.png'>");
changeImg(this);
});
Upvotes: 3