-1

I create a link in ajax callback function and define a class for that, commands that I write on click of this link doesn't work. the code is here:

$('.catpics').click(function(){
   var id=$(this).attr('id');
   $.post('storehouse.php', {
     catid:id,
     btn:'showsub'
   },function(data){
     $('#subcatshelf').append('<a class="catpics" id="'+ data+'">'+data+'</a>');
   });
wogsland
  • 7,351
  • 16
  • 46
  • 79

1 Answers1

0

$('.catpics').click(function(){ only binds to links once. You're looking for .on which will bind to the first object you give it (so you can give it the body of your webpage) and then tell it to listen for clicks on .catpics and since the listener is on the body and not the individual .catpics elements, it wont matter when the links are actually inserted or deleted:

$('body').on('click', '.catpics', function() {
   var id=$(this).attr('id');
   $.post('storehouse.php', {catid:id,btn:'showsub'},function(data){
     $('#subcatshelf').append('<a class="catpics" id="'+ data+'">'+data+'</a>');
   });
});

alternatively you can make click work just fine by pulling out the event handler and just setting up a new clicked listener as you insert a new link:

function clickedCatPic() {
   var id=$(this).attr('id');
   $.post('storehouse.php', {catid:id,btn:'showsub'},function(data){
     var link = $('<a class="catpics" id="'+ data+'">'+data+'</a>');
     $('#subcatshelf').append(link);
     link.click(clickedCatPic);
   });
}

$('.catpics').click(clickedCatPic);
David Zorychta
  • 11,768
  • 4
  • 38
  • 73