Flerex
Flerex

Reputation: 354

Why when I use $(this) in a separate function and I call it inside a .each() it doesn't work?

I was trying to make a clean jQuery code and I put all my things inside a function that I call in a "each". The problem is that nothing happens and in console doesn't appear any error.

That's an example code:

$(function() {
    $('.myElement').each(function() {
        if($(this).children()) {
            myFunction();
        } else {
            myFunction('.myOtherElement');
        }
    });
});

function myFunction(selector) {
    if(!selector) {
        $(this).html('Finish');
    } else {
        $(this).find(selector).html('Finish');
    }   
}

If I put my function content in .each it works, but in a separated function not, and I think that it should work. Why this snippet of code doesn't work?

Upvotes: 2

Views: 98

Answers (2)

Khanh TO
Khanh TO

Reputation: 48982

The problem is the this in your case is not your object inside .each, but is the window object. To bind the this as a jquery object without having to apply the context everytime you want it using call . You could define it as a jquery plugin function

(function($){
    $.fn.myFunction = function (selector) {
    if(!selector) {
        this.html('Finish'); //notice this here refer to jquery object instead of $(this)
    } else {
        this.find(selector).html('Finish');
    }   
  }
})(jQuery);

$(function() {
    $('.myElement').each(function() {
        if($(this).children()) {
            $(this).myFunction();
        } else {
            $(this).myFunction('.myOtherElement');
        }
    });
});

Upvotes: 2

Arun P Johny
Arun P Johny

Reputation: 388416

The execution context(this) is different in this case, you can use .call() to apply it

$(function() {
    $('.myElement').each(function() {
        if($(this).children()) {
            myFunction.call(this);
        } else {
            myFunction.call(this, '.myOtherElement');
        }
    });
});

Upvotes: 7

Related Questions