Frage

call function inside $ (function () {...})

example:

$ (function () {
     makeAlert function (text) {
         alert (text) 
     } 
}); 

I want to call "makeAlert" function from any block.

makeAlert simply call () does not work.

please help!

War es hilfreich?

Lösung

You can't. You've scoped the function to the function it is declared within.

Move it outside so that it is a global. There is no need to delay its definition until the ready event fires.


Alternatively, create a global reference to it within the outer function.

window.makeAlert = makeAlert;

It wouldn't recommend this unless you have some other good reason to keep the function from being declared until the ready event fires as it is more complicated.

Andere Tipps

Functions defined with function XYZ() are scoped to the function block they are in.

They can be made global with window.XYZ = function() {...}. The same applies to variables.

try this:

<script type="text/javascript">
    window = $(function () {
            makeAlert = function (text) {
                     alert (text); 
                    } 
            return {
                makeAlert: makeAlert                  
            }

        }(jQuery))[0]; 
</script>

then call makeAlert("hello");

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top