jQuery: clone elements AND events

前端 未结 4 1742
野的像风
野的像风 2021-01-01 17:19

Whenever I use ajax to dynamically create new content, .clone(), append() etc, the new element looses any triggers and events I programmed =(

After making copy, simp

相关标签:
4条回答
  • 2021-01-01 17:47

    If your handlers are setup using something like $('.class').click( ... )

    Try something like this instead: $('.class').live('click', ...)

    Live applies to elements with the class that may not exist yet.

    0 讨论(0)
  • 2021-01-01 17:53

    Hi I'm having a bit similar use case, I have some dynamically generated content that contains a button, click event is responding to the original button but not the generated one, I've done before :

    $('.someclass').on('click', function() {
    

    but i resolved my problem by replacing the on by live like this :

    $('.someclass').live('click', function() {
    
    0 讨论(0)
  • 2021-01-01 17:56

    I finally got the UI datepicker to work properly. I had to completely remove datepicker BEFORE cloning and add it AFTER cloning elements. The guys at UI should make it easier for us. Go figure!

    Just before cloning:

    //#datepicker
    $("input[name='date']").datepicker( "destroy" );
    $("input[name='date']").removeClass("hasDatepicker").removeAttr('id');
    

    After cloning:

    $("input[name='date']").datepicker({ dateFormat: 'yy-mm-dd', changeMonth: true, changeYear: true, numberOfMonths: 3, showButtonPanel: true});
    
    0 讨论(0)
  • 2021-01-01 18:02

    .clone( true ) does the trick.

    Documentation: http://api.jquery.com/clone/

    0 讨论(0)
提交回复
热议问题