-1

I have this on click:

$('.btn-delete').on('click', function(){console.log('delete')});

I then clone a div:

this.fileTemplate = $('.file:first').remove().clone(true);

Later I add the clone back to the page.

'delete' fails to log

The HTML:

<li class="file">
   <button class="btn-delete">&times;</button>
</li>
panthro
  • 22,779
  • 66
  • 183
  • 324

1 Answers1

1

Since you're not cloning the button itself, but a parent, you need to do a deep clone:

this.fileTemplate = $('.file:first').clone(true,true);
$('.file:first').remove();

http://api.jquery.com/clone/#clone-withDataAndEvents-deepWithDataAndEvents


However, if you're removing the element anyway, you don't need to clone it at all -- just store the div with all of its events by using .detach() instead of .remove():

this.fileTemplate = $('.file:first').detach();

http://api.jquery.com/detach/

To add copies of that element, deep-clone it after it's detached:

clone_copy = this.fileTemplate.clone(true,true);
clone_copy.appendTo('#container');
Blazemonger
  • 90,923
  • 26
  • 142
  • 180
  • re: detach - when I wish to add multiple templates back to the page will I need to use clone? – panthro Jun 20 '14 at 21:46
  • I think by default the second argument (in `clone()`) is ***the same with*** the first argument, so `clone(true)` is enough. – King King Jun 20 '14 at 21:50
  • 1
    @panthro the first should work, that's how you do it, clone the element first and then remove the original element, it's hard to write it in ***one line***, that's your problem. You tried using ***one line*** to solve it, but it's not easy to do that way in this case. – King King Jun 20 '14 at 21:55