简体   繁体   English

在页面上我声明了一个js变量,include js文件似乎无法访问它?

[英]On page I declared a js variable, include js file can't seem to access it?

 <script type="text/javascript">
        $(document).ready(function () { 
            var SOME_ID= 234;

        });

    </script>
<script type="text/javascript" src="<%= HtmlExtension.ScriptFile("~/somefile.js") %>"></script>

The .js file just uses the SOME_ID value, but I'm getting an error saying SOME_ID is not defined. .js文件仅使用SOME_ID值,但是我收到一条错误消息,提示未定义SOME_ID。

Shouldn't this work in theory? 这不应该在理论上起作用吗?

You've declared a local variable within the anonymous function. 您已经在匿名函数中声明了局部变量。 If you want it to be a global variable, use window.SOME_ID = 234; 如果要使其成为全局变量,请使用window.SOME_ID = 234; instead, or move it out of the anonymous function. 而是将其移出匿名函数。

Eg, either: 例如:

<script type="text/javascript">
    $(document).ready(function () { 
        window.SOME_ID= 234;

    });
</script>

or 要么

<script type="text/javascript">
    var SOME_ID= 234;
    $(document).ready(function () { 

    });
</script>

Either way , the external file can access it as either SOME_ID (unqualified) or window.SOME_ID , because global variables are properties of the global object (which is window on browsers). 无论哪种方式 ,外部文件都可以使用SOME_ID (未限定)或SOME_ID window.SOME_ID ,因为全局变量是全局对象(在浏览器中是window )的属性。

You have declared a local variable inside an anonymous function which will be accessible only inside this function. 您已在匿名函数内声明了局部变量,该匿名变量仅可在此函数内访问。 You need to declare it outside: 您需要在外部声明它:

var SOME_ID = 0;
$(function () { 
    SOME_ID = 234;
});

Your variable is defined inside the scope of your anonymous function. 您的变量在匿名函数的作用域内定义。 Move it outside of the ready handler and it ought to work. 将其移出就绪处理程序之外,它应该可以工作。

This variable is scoped to the Function Expression (FE) passed to the ready method - it will not be available outside this scope. 此变量的作用域是传递给ready方法的函数表达式(FE)-在此范围之外将不可用。

You need to make the var global if you want other scripts to be able to access it: 如果希望其他脚本能够访问它,则需要使var为全局变量:

var SOME_ID;
$(document).ready(function () { 
   SOME_ID = 234;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM