简体   繁体   中英

How to get value and change outer variable inside event handlers?

I have empty array. Need to fill it by clicking some links (only if value of current index is not filled already).

$(document).ready(function () {
    var genres_items = []; 

    $('.genre-fill-link').on('click', function() {
        var genre_index = $(this).data('g-index'); // get id of genre

        if(!genres_items[genre_index] { // want to check is this genre filled - get error, undefined variable 
            $.get('/get-genre-list/', {'genre-id', gener_index}, function(data) {  // if genre is not filled yet, want to get data by ajax
                gener_items[gener_index] = data;
            });
        }
    }

    console.log(genres_items); // get empty untouched array, even if links clicked
});

How to fill all elements of array genre_items (every element once by clicking .genre-link )?

How to get values of this array in others handlers and callbacks afterwards?!

Javascript confused me =\ Please help

check my comments and try this:

$(document).ready(function () {

 var genres_items = []; 

 $('.genre-fill-link').on('click', function() {
    var genre_index = $(this).data('g-index'); // get id of genre
    if(!genres_items[genre_index] { // want to check is this genre filled - get error, undefined variable 
        $.get('/get-genre-list/', {'genre-id', gener_index}, function(data){  // if genre is not filled yet, want to get data by ajax
            genres_items[genre_index] = data;
            console.log(genres_items);
        });
     }
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM