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!

有帮助吗?

解决方案

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.

其他提示

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");

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top