简体   繁体   中英

Run JS code on load and on Ajax loaded content

Please see this HTML code:

<div class="grid">
  <h2>First</h2>
  <p>Second</p>
</div>

<div class="grid">
  <h2>First</h2>
  <p>Second</p>
</div>

I was able to change order of elements on page load with this code:

$('.grid').each(function(){
    var p = $(this).find('p'),
        h2= $(this).find('h2');
  h2.insertAfter(p);
});

But there is more content coming with an ajax pagination so I wrapped that inside $(document).ajaxComplete(function(){

Problem now is my code runs only after the ajax content is loaded, I want my code to run on both page load and on ajax loaded content.

Thank you for your assistance.

https://jsfiddle.net/j0fozshv/2/

You can make a method like below and call twice, one after page load and one after ajax complete.

// After page load 
insertDom();

function insertDom(){
  $('.grid').each(function(){
      var p = $(this).find('p'),
      h2= $(this).find('h2');
      h2.insertAfter(p);
  });
}

$(document).ajaxComplete(function(){
    // Do your work
    insertDom();
});

You could extract the stuff you need to do multiple times into a function:

function doMyStuff() {
  $('.grid').each(function(){
    var p = $(this).find('p'),
        h2= $(this).find('h2');
    h2.insertAfter(p);
  });

  // or do what you need. it's just an example
}

And after that, just use your function where you need. On document ready:

$(function () {
     // ... 
     doMyStuff();
});

If you have AJAX stuff somewhere, just call it for success callback:

// just an example !
$(document).ajaxComplete(function() {
    doMyStuff();
});

One more example with jQuery AJAX:

$.get( "/get_some_data", function( data ) {
  doMyStuff();
});

Maybe it makes sense for that function to take some args (eg data that is returned from the server):

function doMyStuff(data) {
  // do what you need
}

And again for your AJAX stuff:

$.get( "/get_some_data", function( data ) {
  doMyStuff(data);
});

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