Question

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!

Was it helpful?

Solution

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);
});

OTHER TIPS

You could do this to set the context:

changeImg.call(this);

See MDN for Function.prototype.call

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'>");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top