Reload javascript file after an AJAX request

前端 未结 10 701
粉色の甜心
粉色の甜心 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:15

    simple way to solve this problem

    $(document).ready(function(){
    
    $('body').on('click','.someClass',function(){
    
    //do your javascript here..
    
    });
    }); 
    
    0 讨论(0)
  • 2020-12-13 21:15

    What do you mean not recognized by jQuery?

    jQuery walks the DOM each time you make a request, so they should be visible. Attached events however will NOT be.

    What isn't visible exactly?

    P.S.: Reloading JavaScript is possible, but highly discouraged!

    0 讨论(0)
  • 2020-12-13 21:16
      var scripts = document.getElementsByTagName("script");
      for (var i=0;i<scripts.length;i++) {
        if (scripts[i].src)
          if(scripts[i].src.indexOf('nameofyourfile')  > -1 )
            var yourfile = scripts[i].src;
      }
      jQuery.get(yourfile, function(data){
      if(data){
         try {
          eval(data);
         } catch (e) {
         alert(e.message);
        }
     }
        });
    
    0 讨论(0)
  • 2020-12-13 21:18

    You can also attach the click handlers to the body so that they never get destroyed in the first place.

    $('body').on('click', 'a', function(event) {
      event.preventDefault();
      event.stopPropagation();
      // some stuff
    })
    
    0 讨论(0)
提交回复
热议问题