Search code examples
jquery-selectorsjqueryjquery-append

append html but there is no selector to new element


I have input for add tag to div ...

and now i want delete tags ... but there is no selector to new tag

$('#filetag').keyup(function (e) {
    var o = $('#filetag'),
        t = $.trim(o[0].value);
    if (e.which == 13 && t) {
        o[0].value = '';
        $('#showtag').append('<img id="delete_tag" title="del" alt="del" class="button8 bdelete" src="/media/images/cleardot.gif">'+t);

    }
});

$('#delete_tag').click(function () {
    console.log('sad');
});

I know must use live but how and for which element? .append cant use live ?


Solution

  • You can bind the event directly to the element that you create:

    $('#filetag').keyup(function (e) {
      var o = $('#filetag'),
        t = $.trim(o[0].value);
      if (e.which == 13 && t) {
        o[0].value = '';
        var img = $('<img/>', {
          id: 'delete_tag',
          alt: 'del',
          className: 'button8 bdelete',
          src: '/media/images/cleardot.gif'
        }).click(function () {
          console.log('sad');
        });
        $('#showtag').append(img).append(t);
      }
    });