JQuery hover and close method

Hardly tried to close Javascript, trying to wrap my brain around function areas, but I think they wrap around me. I looked through a few posts (Niman was the most helpful), but obviously still did not understand. Attempts to start a loop over the hover method in jQuery. Need freeze functions to reach the trigger of more than one action each, but would be happy to make them work with one image exchange each at a time.

$(document).ready(function() {

    imageSource = []; 
    imageSource[0] = 'images/img0.png'  //load 0 position with "empty" png
    imgArea = [];

    for (var i=1; i<11; i++) {

        (function( ){  //anonymous function for scope

            imageSource[i] = 'images/img' + i + '.png';
            imgArea[i] = '#areamap_Img' + i;

            // running console.log here gives expected values for both

            $(imgArea[i]).hover(   //imgArea[i] (selector) works correctly here

                function() {
                    $('#imgSwap').attr('src',imageSource[i]);  // imageSource[i] is undefined here
                },
                function() {
                    $('#imgSwap').attr('src','images/img0.png');
                });

        })(); // end anonymous function and execute

    }; // for loop

}); 

Tried the idea of ​​using an anonymous function to determine the scope from another jQuery post. It seems to work fine, but throws undefined for the array value in the first hover function, I think, because it is an internal function (sources of hard coded image work well there).

+3
1

, var i. i, . , i , i == 11 ( , ). , i , :

for (var i=1; i<11; i++) {

    (function( ){  //anonymous function for scope                
            var index = i; // The important part!

            // It not technically necessary to use 'index' here, but for good measure...
            imageSource[index] = 'images/img' + index + '.png';
            imgArea[index] = '#areamap_Img' + index;

            $(imgArea[index]).hover(

                    function() {
                            $('#imgSwap').attr('src',imageSource[index]);  // Here where `index` is necesssary.
                    },
                    function() {
                            $('#imgSwap').attr('src','images/img0.png');
                    });

    })(); // end anonymous function and execute

}; // for loop

, , . ; :

var imageSource = []; 
var imageSource[0] = 'images/img0.png'  //load 0 position with "empty" png
var imgArea = []

"var" . ( , .)

+11

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


All Articles