开发者

How to reference functions with document ready?

开发者 https://www.devze.com 2023-04-03 19:20 出处:网络
I have some functions in a JQuery document ready method that I would like to reference from other external files, but I keep getting a function un开发者_StackOverflowdefined. How can I make those glob

I have some functions in a JQuery document ready method that I would like to reference from other external files, but I keep getting a function un开发者_StackOverflowdefined. How can I make those global?

ex.

external file 1

    $(function ()
    {
         function DoSomething()
         {    
            Do something
         }    
    });


external file 2

    $(function ()
    {

        Call DoSomething()
    )};


declare the functions outside the jQuery escope.

external file 1


         function DoSomething()
         {    
            Do something
         }    


external file 2

    $(function ()
    {

        Call DoSomething()
    )};


You can either define the function outside .ready() (as the other answers suggest), or you can take advantage of the fact that the window object is the global scope. So, you can make them global like this:

$(function(){
    function doSomething(){
        // …;
    }
    window.doSomething = doSomething;
});

Note that in this case they’ll only be defined after .ready() runs — if you want to use them immediately in another file (i.e. not inside an event handler or another .ready() function), this won’t work.


You probably want to define functions outside ready blocks. That does not hurt. Only executing a function outside a ready block can cause issues if it uses the DOM before it's ready.

Defining does nothing (yet), and as such does not use the DOM. So it does not need to be inside a ready block; doing so only constrains the places where you can access it, which is basically only a disadvantage.

external file 1

function DoSomething()
     {    
        Do something
     }   


Whenever possible, declare functions outside of the ready check.

external file 1

function DoSomething()
{    
    Do something
}    

external file 2

$(function ()
{
    Call DoSomething()
)};
0

精彩评论

暂无评论...
验证码 换一张
取 消