0

I have multiple a elements. I'm trying to handle the click event to display on alert the id of the clicked link but nothing is happening. Please help!

$(".sites").click(function() {
  alert('handlin');
  alert($(this).attr("id"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" class="sites" id="1">test1</a>
<a href="#" class="sites" id="2">test2</a>

Links are generated here:

$.getJSON(categoriesURL, {
  term: request
}, function(data) {
  var iHtml = '';
  $.each(data, function(i, item) {
    if (10 <= i) 
      return false;
    iHtml += '<li><a href="#" class="sites" id="'+item.id+'">' + (item.title || '') + '</a></li>';
  });
  $('#categories').append(iHtml);
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Sz3jdii
  • 507
  • 8
  • 23

1 Answers1

1

you have to bind event after ajax call done

 function bindButtonClick(){
       $(document).on('click', '.sites', function() {
      alert('handlin');
      alert($(this).attr("id"));
    });
    }

$.getJSON(categoriesURL, {
  term: request
}, function(data) {
  var iHtml = '';
  $.each(data, function(i, item) {
    if (10 <= i) 
      return false;
    iHtml += '<li><a href="#" class="sites" id="'+item.id+'">' + (item.title || '') + '</a></li>';
  });
  $('#categories').append(iHtml);
  bindButtonClick();
});
Ahmed Yousif
  • 2,298
  • 1
  • 11
  • 17