0

I'm new in Jquery. I'm trying to do some basic function in Jquery and AJAX and generating HTML on the fly. but for "$(document).ready(function ()" it's not working.

$(function () 
{
 $.ajax({ 
  type: "POST",                                     
  url: 'api.php',                  //the script to call to get data          
  //data: { id:2 },                  //you can insert url argumnets here to pass to api.php
                                   //for example "id=5&parent=6"
  dataType: 'json',                //data format      
  success: function(data)          //on recieve of reply
  {
    $('#root').append('<div id="try"></div>');
    for(var i = 0; i < data.length; i++)
    {
      var cssId = 'writings'+ i;
      var id  = data[i][0];
      var name = data[i][1];
      //$('#root').append("id: "+id); //Set output element html
      $('#try').append('<div class="names" id="'+cssId+'">'+name);
      $('#'+cssId).append('<a href="#" class="edit" id="img1"><img src="img/edit.png"></a>');
      $('#'+cssId).append('<a href="#" class="delete" id="img2"><img src="img/delete.png"></a>');
      $('#try').append('</div>');
    }
  } 
 });
});

$(document).ready(function () {
$('#img1').on('click', function() {
$(this).remove();
});
});

for the first block of code it's generating a html like this [1]: http://postimg.org/image/nphmjutlz/ "screenshot". but when i click in the edit or delete buttons it's not working. According to my code it should be removed.

Thanks in advance.

Mathijs Flietstra
  • 12,900
  • 3
  • 38
  • 67
nixon1333
  • 531
  • 1
  • 9
  • 23

1 Answers1

2

use this (outside document.ready):

$(document).on('click','#img1', function(){
   $(this).remove();
});

this works without matter when you create the element (in this case #img1).

Your code only works if #img1 exist before $('#img1').on('click', .....

Michael Aguilar
  • 766
  • 8
  • 16