append html but there is no selector to new element

454 Views Asked by At

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 ?

3

There are 3 best solutions below

0
On BEST ANSWER

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

Create jquery object, and store event with it.

var img = $('<img></img>').attr({'id':"delete_tag", ../**attr here**/.. })
                          .live( /*live here*/).click(/*or click here*/);

And then append to

$('#showtag').append(img);
0
On

2 possibilities:

1/ use the livefunction:

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

2/ add click event on created element:

$('<img id="delete_tag" title="del" alt="del" class="button8 bdelete" src="/media/images/cleardot.gif">'+t)
  .click( function {
    console.log('sad');
  })
  .appendTo('#showtag');