访问 $(function () { ... }) 中的代码

Accessing Code inside $(function () { ... })

我有一个 .NET Web 控件,其中包含一些 JavaScript 结构如下:

<script type="text/javascript">

    function doSomethingImportant() {
        // Do something important here...
    }

    $(function () {

        // A bunch of JavaScript/jQuery code here...

    });

</script>

doSomethingImportant() 函数位于我的 $(function() { ... }) 块之外,因此可以从托管我的 Web 控件的页面上的 JavaScript 调用它。

但我希望此函数能够访问 $(function() { ... }) 块中的一些代码。这可能吗?有没有更好的方法来构建它?

如果您在 jquery 函数中的 window 对象上添加代码,您可以从外部函数调用它。

例如

<script type="text/javascript">

    function doSomethingImportant() {
        // Do something important here...
       window.myfunc();
    }

    $(function () {

        // A bunch of JavaScript/jQuery code here...

      window.myfunc = function(){
      }

    });

</script>