简体   繁体   中英

jquery page javascript not loading on ajax div

[REVISED]

Hi, thanks for the feedback guys. I revised by question btw. To make things clearer here's my html page (sample only)

<html>
<head>
<body>
     <form>
     <div class="loadAjax"></div>
     <div class="toggle">[form inputs here]</toggle>
     <a href="#" class="btn">Submit</a>
     </form>
     <script>[several js scripts here]</script>
</body>
</html>

And here's my main js file:

$(function() {
     [some lines here]
     $('.toggle').toggle();
     $('.btn').on('click', function(e) {
          e.preventDefault();
          $.ajax({
               url: 'http://example.com/ajaxpage',
               type: 'POST',
               data: $('form').serialize(),
               beforeSend: function() {
                     ...
               },
               success: function(data) {
                     $.getScript('js/main.js');
                     $('.content').html(data);
               }
          });
     });
});

The page that will be loaded in div.loadAjax.

<div class="toggle">ajax page load</div>

Taking this as an example, the toggle on the main page seems to work. But the div.toggle on the div.loadAjax doesn't. I need to set the $.getScipt() in order to reload the main.js file again. Shouldn't the div.loadAjax inherit the main.js since it is loaded already in the first place? Why do I still need to reload it again using the $.getScript() ?

NOTE: I'm using ajax to do a form post on a PHP page.

Thanks again!

The code for toggle was already executed on your first page load. That will not execute again automatically without a page reload, otherwise you have to trigger it again or should load your script again as you did now.

Try attaching it to click event and trigger it dynamically using .trigger

$(function() {
     [some lines here]

     $(".toggle").on("click", function(){
                           $('.toggle').toggle();
                             });

    $('.toggle').trigger("click");

     $('.btn').on('click', function(e) {
          e.preventDefault();
          $.ajax({
               url: 'http://example.com/ajaxpage',
               type: 'POST',
               data: $('form').serialize(),
               beforeSend: function() {
                     ...
               },
               success: function(data) {

                     $('.content').html(data);
                     $('.toggle').trigger("click");
               }
          });
     });
});

Why don't you use the $.load() method: http://api.jquery.com/load/

This will let you perform an Ajax call, inject the results back onto the DOM of your page and also supports executing scripts loaded via the request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM