未在<a> elements

时间:2018-09-04 07:49:16

标签: javascript jquery

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);
});

1 个答案:

答案 0 :(得分:1)

您必须在ajax调用完成后绑定事件

 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();
});