jQuery each - Clarification

Asked

Viewed 54 times

2

I need every x seconds a li my menu is hidden and I have this code:

$('.area-menu .close').click(function(){
    delayed();
});

function delayed() {
    var liMenu = $('.area-menu li').not('.marginless');
    var time = 1000;

    liMenu.each(function(){
        setTimeout(function() {
            console.log($(this));
        }, time);
        time += 1000;
    });
}

But when I soon $(this) he doesn’t return anything to me. How would I give a hide() in each li from my menu? And where am I missing?

  • I figured out what it is. And I kind of figured out why.

2 answers

1


You have a double context problem. Inside setTimeout the context is not the same as the function where it was run. The this refers to window (global context) and not the element iterated by jQuery. Inside a loop you can use the arguments passed to callback (index and element), or you can create a reference to this with var el = this; for example, out of setTimeout, but inside the loop.

Solution:

function delayed() {
    var liMenu = $('.area-menu li').not('.marginless');
    var time = 1000;

    liMenu.each(function(i, el) {
        // ou var el = this;
        setTimeout(function() {
            console.log($(el));
        }, time);
        time += 1000; // ou somente  "}, time * (i + 1));"
    });
}

1

Usually what one does is instantiate this out of the callback method. ex:

var self = this;
setTimeout(function() {
    //aqui use a variável self para acessar o objeto que chamou o callback
    //no caso se fosse window mesmo não faz muita diferença já que você pode utilizar o objeto window
}, time);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.