jQuery, how to rebind html-elements after .load()

前端 未结 2 1154
感情败类
感情败类 2021-01-14 22:37

I have a html-component that will be reload after a button has been clicked. Some elements of the component are bound to click and hover handlers. Everything is working fin

相关标签:
2条回答
  • 2021-01-14 23:07

    I'm not sure of the way you are binding your events, but basically, if you are doing something in this way :

    $('.your-class').on('click', function (e) {[...]});
    

    You may have better to delegate it to the document, that is not reloaded.

    $(document).on('click', '.your-class', function (e) {[...]});
    

    You can be sure that even the elements that does not exists at the script execution time will be binded aswell, be cause they will be a part of your document, later.

    0 讨论(0)
  • 2021-01-14 23:10

    You should be able to call the .load() method AND create a callback in which you can rebind the elements.

    For example:

    $(document).ready(function() {
        ...initially bind all event handlers for page (including elements to be reloaded)...
    
        $("#someButton").on("click", function() { 
            $("#elementToReload").load("page-to-load.html", function() {
                 ...bind all event handlers for this and containing elements here...
            });
        });
    });
    


    Let me know if you have any questions on this. Good luck! :)

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