Reload javascript file after an AJAX request

前端 未结 10 728
粉色の甜心
粉色の甜心 2020-12-13 20:25

After the request, the new elements created are not recognized by the event handlers in my jQuery code.

Is there a way to reload the file to re-register these events

10条回答
  •  清歌不尽
    2020-12-13 21:08

    To increase the website performance and reduce the total file’s size return, you may consider to load JavaSript (.js) file when it’s required. In jQuery, you can use the $.getScript function to load a JavaScript file at runtime or on demand.

    For example,

    $("#load").click(function(){
        $.getScript('helloworld.js', function() {
            $("#content").html('Javascript is loaded successful!');
        });
    });
    

    when a button with an Id of “load” is clicked, it will load the “helloworld.js” JavaScript file dynamically.

    Try it yourself In this example, when you clicked on the load button, it will load the “js-example/helloworld.js” at runtime, which contains a “sayhello()” function.

    
    
    
    
    
    
    
      

    Load Javascript dynamically with jQuery


提交回复
热议问题