Binding an Event Sequence Using a FOR Loop

Hi. I am trying to associate a sequence of events with multiple divs using the javascript jQuery library. Here is what I am trying to do.

There will be a lot of divs on the screen with id div1 div2 div3 ... div10 etc. However, only the first div with id 'div1' will be displayed with all other hidden divs. When the user is hovering on div1, div2 should be displayed, and when he is hovering on div 2, div 3 should be shown, and this should continue sequentially until the last div.

I managed to find a solution using the following jQueries method.

$('div').each(function(){
    $(this).mouseover(function(){
        $(this).next().show();
    });
});

However, since I recently learn javascript, I wanted to redo it using the FOR loop, and it will not work.

for (var i=1; i<11; i++){
    $('#div' + i).mouseover(function(){
        $('#div' + (i+1)).show();
    });
}

, , , , "i" , , . -, , , , jQuery.next(), javascripts FOR. .

+3
4

, divs i, for 11. , -

for (var i=1; i<11; i++){
    $('#div' + i).mouseover(function(){
        var index_string = $(this).attr('id').substring(3), //return, say the string '6'
            index = parseInt(index_string, 10); //convert it to a number
        $('#div' + (index+1)).show();
    });
}

, :

for (var i=1; i<11; i++){
    (function() {
        var j = i;
        $('#div' + j).mouseover(function(){
            $('#div' + (j+1)).show();
        });
    })();
}
+3

- :

for (var i = 1; i < 11; i++){
    $('#div' + i).mouseover(function () {
        $('#div' + (i+1)).show();
    });
}

i 10 , i, (11 , , ). , mouseover '# div12', , , .

, - :

for (var i = 1; i < 11; i++) {
    (function (j) {
        $('#div' + i).mouseover(function () {
            $('#div' + (j+1)).show();
        });
    }(i));
}

j ( j, i ), .

, , .

+3
for (var i=1; i<4; i++){
        (function(j){
            $('#div' + j).mouseover(function(){           
            $(this).next().show();
            })
        }(i));
    }
+2
source

if you do not need this object, you can do the following:

for (var i=1; i<11; i++){
    $('#div').mouseover(function(j, e){
        $('#div' + (j+1)).show();
    }.bind(null, i));
}

and if you still need (this) object,

for (var i=1; i<11; i++){
    $('#div').mouseover(function(j, e){
        $('#div' + (j+1)).show();
    }.bind($('#div'), i));
}
0
source

Source: https://habr.com/ru/post/1795181/


All Articles