How to make $(document).ready() functions available globally?
I have an interesting question here that may sound pretty silly, but here goes. Using jQuery's ready function I have defined some functions like so:
$(function(){
var function1 = function(data){
//do something
}
var function2 = function(data){
//do something else
}
});
For some reason, in order for IE to render what I am using correctly, it must be done in the $(document).ready()
function. However, I need to trigger these functions once I have a dataset from the server-side. So I thought I would do something like this:
Object.Namespace.callFunction = function(data){
function1(data);
}
...to be placed outside the ready function in a script so that I could call it directly.
Unfortunately, I know this doesn't work because well, it does not seem logical and I have tried it!. I made all these functions arbitrary because it does not matter the content, but rather the concept. I have also tried using event handlers to trigger the function once I get that data -- to no avail! What is the best way to make functions inside the $(docume开发者_Go百科nt).ready()
global?
If you are defining global functions there is no reason to have them in the document ready. The only things that should go in the document ready are things that need to wait until the document is ready in order to act. Defining function can happen before the document is ready.
// Defining the functions in the global scope.
var function1 = function(data){
//do something that requires the dom to be ready.
}
var function2 = function(data){
//do something else that requires the dom to be ready.
}
$(function() {
// Running the functions when the document is ready.
function1();
function2();
});
If you (for stylistic reasons) want to write the function inline with your $(document).ready, You can do it this way:
var app={}; /*Use whatever your apps name is, abbreviated (something short)*/
$(function()
{
app.function1 = function(data) { };
app.function2 = function(data) { };
// now you can call all functions inside and outside this ready function with the app. prefix
// if you also want a local reference to the function without the app. prefix, you can do:
var function1 = app.function1 = function(data) { };
});
what about
function function1(data){
//do something
}
function function2(data){
//do something else
}
$(function(){
// if you need to call inside ready
function1();
function2();
});
精彩评论