How to store an id from an API in a variable so that on an on click it can be used to locate information?

时间:2017-04-09 23:45:49

标签: javascript jquery api

On an on click function I have album images from an API appear. When clicking on the album image I have an overlay with the image.

I am trying to attach other information about the album to the overlay. Is it possible to store the albums id in a variable so that on click just the information from one particular album is displayed? I can get all of the ids in this function as a variable, but can not work out how to store each one as an individual variable, to use on the on click function. Any suggesstions are appreciated.

     function displayAlbums(data) {

                    var html = '<ul>';
                     $.each(data.tracks, function(i, eachAlbum) {
                     html += '<li class="albumImage">';
                     html += '<img src="' + eachAlbum.album.images[0].url + 
                  '">';
                     html += '</li>';

                    var id = eachAlbum.album.id;
                         console.log(id);   // all albums id's are showing 
                      in console

                    }); // closes each
                     html += '</ul>';

                      $("#albumImages").html(html);

                    } //closes displayAlbums function

3 个答案:

答案 0 :(得分:1)

Store as data attribute on each <img> or <li>

html += '<img data-album_id="' +eachAlbum.album.id +'" src="' + eachAlbum.album.images[0].url + '">';

Then a click handler can access it directly from the element itself

$("#albumImages").on('click', '.albumImage img', function(){
   console.log('album id=', $(this).data('album_id'));
})

答案 1 :(得分:1)

You can use data-id attributes on img or li, whichever makes sense inside your $.each and access them in onclick listener, like this:

function displayAlbums(data) {

    var html = '<ul>';
    $.each(data.tracks, function(i, eachAlbum) {
        html += '<li class="albumImage">';
        html += `<img src="${eachAlbum.album.images[0].url}" data-id="${eachAlbum.album.id}">`;
        html += '</li>';

        var id = eachAlbum.album.id;
        console.log(id); // all albums id's are showing in console

    }); // closes each
    html += '</ul>';

    $("#albumImages").html(html);

}

More on using data attributes(MDN)

More on template literals, as used here

html += `<img src="${.....`

答案 2 :(得分:0)

you could add the id as a data-id attribute, so it would look like this:

html += '<img src="' + eachAlbum.album.images[0].url + '" data-id="' + eachAlbum.album.id + '">';