简体   繁体   中英

How to call multiple js functions on document.ready without putting them jQuery(document).ready(function(){});

Is there a way to 'bind' multiple functions to jQuery's document.ready function without actually calling them in that method. Basically I don't know which functions I might be calling in document.ready until the page is generated.

There are several ways to handle this. (You probably want #2.)

  1. Use an options class to determine what happens, then have static code which checks the options to see which functions to call.

  2. Wait until you know what functions to call, and add each of them into $(document).ready( whatever ) as separate lines.

     $(document).ready(function1); $(document).ready(function8);
  3. Dynamically create the body of the one function you write into $(document).ready(...)

If you call $(document).ready() anytime after the document was already ready, it will just execute immediately: ( http://jsfiddle.net/Ew8b3/ )

var afterReady = function(){
    $(document).ready(function(){
      $('body').append('<div>waited 5 secs</div>');
    });
};

$(document).ready(function(){
  setTimeout(afterReady, 5000);
});

I'm not sure how/when you will know what you want to execute, but know that you can use document.ready at any time.

I'm not sure I quite understand what you mean by bind without calling. But what you can do is pass the functions in as variables (for example func1, and func2)

this way you can do something like:

$(document).ready(function() { 
                      var func1 = ...;
                      var func2 = ...;
                      doSomething(func1,func2);
}

doSomething(f1,f2){
   return f1()+f2("somedata");
   // or whatever you wanna do
}
$(function() { alert('ready'); });

is the same as

Jquery(document).ready(function() { alert('ready'); }):

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