简体   繁体   中英

Detect image click after append using jQuery

I have the following code:

   $('#spotifyAlbum').click(function () {
             var albums = {};
             $.ajax({
                 url: 'https://api.spotify.com/v1/me/albums',
                 headers: {
                     'Authorization': 'Bearer ' + token
                 },
                 success: function (response) {
                     $('#testSpotifyAlbumsContainer').show();
                     for(var i = 0; i < response.total; i++)
                     {
                         $('#testSpotifyAlbums').append("<img src='" + response.items[i].album.images[0].url + "' uri='" + response.items[i].album.uri + "' class='spotifyAlbum'>");

                     }

                 },
                 error: function (response) {
                     console.log(response);
                 }
             });
         });

   $('.spotifyAlbum').click(function () {
         console.log("hej");
     });

But when I click on one of the images, nothing is printed out in the log. What am I doing wrong?

Edit

I solved It by adding this:

  $(document).ajaxComplete(function () {
             $('.spotifyAlbum').click(function () {
                 console.log("Hej");
             });
         });

Standards jQuery selectors like the one you used $('.spotifyAlbum').click() works only on elements which are present in the DOM in time of page load. If you create new DOM elements for example by your AJAX request this click event listener will not notice these elements and will not handle clicks on them.

There is a workaround for this case in jQuery. Before version 1.7 there was a .live() method, for 1.7+ use $(document).on('click', '.spotifyAlbum', function() {}); This selector will keep listening on all clicks on the whole document but will trigger only on those which were made on elements with .spotifyAlbum class.

This will works:

 $('#spotifyAlbum').click(function () { var albums = {}; $.ajax({ url: 'https://api.spotify.com/v1/me/albums', headers: { 'Authorization': 'Bearer ' + token }, success: function (response) { $('#testSpotifyAlbumsContainer').show(); for(var i = 0; i < response.total; i++) { $('#testSpotifyAlbums').append("<img src='" + response.items[i].album.images[0].url + "' uri='" + response.items[i].album.uri + "' class='spotifyAlbum'>"); } }, error: function (response) { console.log(response); } }); }); $(document).on('click', '.spotifyAlbum', function () { console.log("hej"); });

I know you have already solved it but just providing explanation for your understanding. I don't have enough reputation to add it as a comment.

It didn't work earlier because you were trying to attach event handlers to future elements, the ones which were not there at the time of attachment but were added later after ajax call.

You could have also solved it by attaching the event handler to the document itself instead of the actual elements in your original code.

$(document).on("click",".spotifyAlbum",function(){
    console.log("Hey");
})

should have worked too. More about jQuery on method here .

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