jQuery each - Clarification

2

I need every x seconds a li of my menu to be 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 immediately $(this) it does not return anything to me. How would you give a hide() that is in each li of my menu? And where am I going wrong?

    
asked by anonymous 10.02.2016 / 21:34

2 answers

1

You have a double context problem. Within setTimeout the context is not the same as the function where it was run. The this refers to window (global context) and not to the element iterated by jQuery. Within a loop you can use the arguments passed to the callback (index and element), or you can create a reference to this with var el = this; for example outside of setTimeout, but within 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));"
    });
}
    
10.02.2016 / 21:45
0

In general, what is done is to 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);
    
10.02.2016 / 21:48