简体   繁体   中英

Onclick event not triggered on span elements appended after AJAX call

I am retrieving some data using Ajax and appending it as span element. Below is the simplified version of the code.

 function fetchPost() {

      $.getJSON(urlContent, function(data) {
        $.each(data.query.pages, function(i, item) {
            $("#feed").append("<span id='random'> randomtitle </span>");  

          }

        });



      });

      return 1;
}

$(document).ready(function(){

 $('span').click(function() {
    var text = $(this).text();
    alert(text);

    });

  });

The onclick event is not triggering for span elements which was appended with the help of the AJAX call. The span elements which were present in the html before is responding to onclick event. What should I do?

The problem is you are trying to listen to elements that don't yet exist. The solution is to use event delegation, and listen to the parent element:

$("#feed").on('click', 'span', function() { /* ... */

http://api.jquery.com/on/

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