简体   繁体   中英

jQuery - How to create a new function to simulate document.ready on ajaxComplete?

I am using the FoundationPress theme (Wordpress Theme with the Foundation 6 from Zurb framework), and i'd like to ajaxify it. (using Ajaxify Wordpress Site plugin).

Now my problem is that most of the javascript that's on my website isn't working after an ajax load.

I have found that this is because most of the javascript in the foundation.js file is executed on document.ready , and that this event is not being triggered when loading a page with ajax .

I understand that it is not possible to trigger the document.ready event after page load. And after seeing multiple threads here, it appears the only solution is to create a new function with the code that's needed on document.ready and ajaxComplete.

BUT, Foundation has a lot of javascript files, and most of it is above my level of understanding. Is there any way to create a function that would automate this ?


EDIT
I tried this. I need to pass jQuery as an argument or the code inside initialiseSticky will not work. It works for document.ready but not for ajaxComplete , any idea ?

jQuery(function($) { 
    console.log('document ready- sticky');
    initialiseSticky($);
});
$(document).ajaxComplete(function ($) {
    console.log('ajax complete- sticky');
    initialiseSticky($);

}(jQuery));

function initialiseSticky($) {
//my code
}

Not sure about foundation.js but if you can make a variable, FooBar for example, assign the function() in $(document).ready() to that variable, and then on ajaxComplete call the variable/function again to "re-trigger" it, like below:

jsFiddle

 var res = $('#result'), bg = $('#bg-div'), btn = $('#btnTest'), i = 0, // just for demo to illustrate that it is changing FooBar; $(document).ready(FooBar = function() { bg.delay(200).fadeIn(2000); console.log('document is ready ' + i++); }); // simulate ajaxComplete btn.on('click', function() { res.text('just dummy text here ' + i); bg.fadeOut(500); FooBar(); }); 
 body { margin: 0; padding: 0 } #bg-div { background-color: orange; width: 100%; height: 100%; position: fixed; z-index: -1; display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <div id="bg-div"></div> <button id="btnTest">Click Me</button> <div id="result"></div> 

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