reinitialize other javascript functions after loading a page with ajax pagination

前端 未结 1 1011
梦谈多话
梦谈多话 2021-01-18 03:05

Apologies, a total newb here. How can I load other plugins, and let other separate scripts function after loading an ajax generated page? This is my curent code:

<         


        
相关标签:
1条回答
  • 2021-01-18 03:27

    When you load ajax-generated markup it will not retain the functionality it had before. In your example above, you're initialising things when the DOM is ready to be acted upon. In order to make sure any plugins, etc, are running after you perform the ajax request you need to reinitialise them.

    Given your code sample above, I'd recommend a little restructuring. For example, you could create a function called init which you could call to initialise certain plugins:

    function init () {
        $("#plugin-element").pluginName();
    }
    
    jQuery(document).ready(function () {
        // Initialise the plugin when the DOM is ready to be acted upon
        init();
    });
    

    And then following this, on the success callback of you ajax request, you can call it again which will reinitialise the plugins:

    // inside jQuery(document).ready(...)
    $.ajax({
        type: 'GET',
        url: 'page-to-request.html',
        success: function (data, textStatus, jqXHR) {
            // Do something with your requested markup (data)
            $('#ajax-target').html(data);            
    
            // Reinitialise plugins:
            init();
        },
        error: function (jqXHR, textStatus, errorThrown) {
            // Callback for when the request fails
        }
    });
    
    0 讨论(0)
提交回复
热议问题