简体   繁体   中英

jQuery document.ready and function placement

I have a function:

function pickPhrase(phraseArray){
    var phraseShuffled = fyshuffle(phraseArray);
    var phrasePick = phraseShuffled[0];
    return phrasePick;
};

Inside a $(document).ready(function(){ /*code*/ }); , I assign it to an onClick event in an html tag. (Yes, I know onClick inline is bad form - for now I am using it!)

Here's the interesting thing: it only works (ie: executes the function on click) if pickPhrase is defined outside the $(document).ready function. When it is INSIDE, chrome console tells me "ReferenceError: pickPhrase is not defined."

However, console.log(pickPhrase(phraseArray)); WILL work from inside the $(document).ready regardless of whether phraseArray is defined inside or out.

So... why?

When you declare a function inside another function, it's local to that function. The "ready" handler is a function, and so there you go.

For an "onfoo" attribute handler, functions referenced must be global.

If you must assign your event handlers that way — and please don't — you can "export" a function from the "ready" handler with an explicit assignment:

$(function() { // don't really need $(document).ready( - just $( is enough

  function pickPhrase(phraseArray){
    var phraseShuffled = fyshuffle(phraseArray);
    var phrasePick = phraseShuffled[0];
    return phrasePick;
  };

  window.pickPhrase = pickPhrase;
});
$(document).ready(function(){ /*code*/ });

Because /* code */ is in an anonymous function that is executed by the ready function variables and functions declared inside of it will only be available in that scope, not the global scope. Using console.log inside there works because it's the same scope, but trying to access it using onclick in the html assumes that it is in the global scope, unless you use namespacing and provide a mechanism to get to it.

If the function is inside $(document).ready(){ function thisFunction(){}}; then doing inline onClick="thisFunction();" will not see what's inside the ready()

Scope. When defined outside your ready handler, phraseArray is a global variable accessible from any of the scopes defined inside the global scope. When defined inside, phraseArray's scope is limited to the confines of the function.

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