javascript/jquery传递变量

hel*_*llo 0 javascript variables jquery parameter-passing

我想知道是否有一种方法可以传递这样的变量:

<script type="text/javascript">
width = 300;
</script>

<script type="text/javascript">
(function(){
    var k = width;
    alert(k);
});
</script>
Run Code Online (Sandbox Code Playgroud)

我正在努力学习如何将宽度传递给变量k.我不想做var width =300有没有办法做这样的事情?所以最终我可以把底部脚本(function(){...});放到一个文件中,我可以这样做

<script type="text/javascript">
width = 300;

//more variables if needed

//height = 300;
//name = "example";
//...
</script>

<script type="text/javascript" src="thefile.js"></script>
Run Code Online (Sandbox Code Playgroud)

所以我可以添加更多变量

谢谢!

Der*_*會功夫 5

<script type="text/javascript">
    window.$vars = {
        width: 300
    };
</script>

<script type="text/javascript">
    (function(){
        var k = window.$vars.width;
        alert(k);
    })();
</script>
Run Code Online (Sandbox Code Playgroud)

将变量放在全局范围内就可以了.