简体   繁体   中英

Function does not work in Javascript

i have this function in jQuery:

$(document).ready(function(){ function MyFunction() {alert('Hello!');} });

(For example only)

but, i'm want call this function with regular Javscript this way:

if(x == y){MyFunction();}

(For example only)

and i'ts not work.

However, When i try it:

function MyFunction(){alert('Hello!');} if(x == y){MyFunction();}

(Without jQuery function)

it's work.

Why?

if you put the function outside of the .ready() and call it in the ready function it will work, if you put it in the ready() and call it outside of ready it will give you an error you may have a function declared outside of ready state using jQuery code and call it inside.

    function MyFunction(){
    alert("hello!!");
    }
    //on ready
   $(document).ready(function(){
   if(x==y)
    MyFunction();
   });

I understand your issue like this {but not really clear what you are looking for imho}

Define function:

function MyFunction(){alert('Hello!');}

Call it on document ready:

$(MyFunction);

Now whenever you want, you could use:

if(x == y){MyFunction();}

this line:

if(x == y){MyFunction();}

should also be in the document.ready statement.

if you call it outside it will run before the function was actually defined and thus it will fail.

Lesonchi has it right. The issue is 'scope'.

The $(document).ready(...) call takes a function which is it's own scope (Javascript only has function scoping). So, anything defined inside the function you are passing to that call is ONLY available inside that function.

Based on your question, I assume you wanted to be able to call that MyFunction method elsewhere in the code and not just in the $(document).ready() - so, defining it outside the that call would give it 'global' scope, and hence could be used elsewhere in your code:

function MyFunction(){ /* do something */ }

$(document).ready(function(){
  MyFunction();    // call it in this scope
});

// call it in 'global' scope
if (x == y) {
  MyFunction();
}

See Also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope

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