开发者

append html but there is no selector to new element

开发者 https://www.devze.com 2023-02-23 04:48 出处:网络
开发者_运维百科I have input for add tag to div ... and now i want delete tags ... but there is no selector to new tag

开发者_运维百科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 ?


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


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


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');
0

精彩评论

暂无评论...
验证码 换一张
取 消