how to replace HTML with jQuery but keep event bindings

前端 未结 2 1235
难免孤独
难免孤独 2021-01-12 18:32

this is more a strategic question than a specific one, but I think it\'s precisely asked so here goes:

let\'s say I have a page or ap that has 3 separate sections.

相关标签:
2条回答
  • 2021-01-12 19:13

    You could use Event Delegation, so you don't have to re-bind.

    0 讨论(0)
  • 2021-01-12 19:18

    You will need to divide the problem into two sections

    Handling events
    This can be done using event delegation using $.on(). ie instead of registering events on the element you register on a parent which will not be removed
    Ex:

    $('.container').on('click', 'a', function(){
        //do something
    })
    

    Handling widgets like draggable
    Here I think you are out of luck because I don't see any other way than to reinitialize those widgets once the new dom elements are added
    Ex:

    var ct = $('.container').html('');
    ct.find('li').draggable({})
    
    0 讨论(0)
提交回复
热议问题