简体   繁体   English

如何将变量传递到另一个js文件

[英]how to pass variable to another js file

I am trying to pass a variable from a.js file to b.js file. 我正在尝试将变量从a.js文件传递到b.js文件。

a.js a.js

var test='test string';

b.js b.js

alert(test);

I am sure a.js is included in my html before b.js but I still got ' test ' is not defined error. 我确定a.js包含在b.js之前的html中,但是我仍然遇到' test '未定义的错误。 Are there anyway to debug this? 反正有调试吗? Thanks a lot! 非常感谢!

要确保将测试分配给全局范围,请执行以下操作:

window.test = 'test string';

I don't think you are as much passing a variable in this case as making it accessible. 在这种情况下,我认为传递变量不是使它易于访问。 At some point you may want to look at this (scope vs. context) . 在某些时候,您可能要看一下(范围与上下文) It may seem like a bit much this early on, but it will come in handy sooner than you think. 可能看起来有点早,但是比您想像的要早得多。

To debug: 要调试:

a.js: a.js:

var a = 'a';
console.log(b);

b.js: b.js:

var b = 'b';
console.log(a);

Are you using top-down execution in your javascript files? 您是否在JavaScript文件中使用了自上而下的执行方式? Using the global scope - unless its a constant or a helper function - its almost always a bad idea... 使用全局范围-除非它是常量或辅助函数-否则几乎总是一个坏主意...

At a minimum, define functions if not classes and pass variables between those instead... 至少要定义函数(如果不是类的话),并在它们之间传递变量……

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

相关问题 如何调用netlify函数并在另一个js文件中传递变量? - How to call netlify function and pass variable within another js file? 如何将变量从服务器js文件传递到另一个 - how to pass variable from server js file to another 如何将变量传递到.js文件 - how to pass variable into .js file 如何将变量传递给一个js文件到onload function中的另一个js文件 - how to pass variable to one js file to another js file inside onload function 如何将变量从一个.js文件传递到另一个.js? - How can I pass a variable from one .js file to another .js? React.js 如何从另一个没有导出的 js 文件中传递变量 - React.js How to pass a variable from another js file that does not have export 如何将一个页面上的js变量集传递到另一个js文件 - How to pass a js variable set on one page onto another js file 如何将全局变量值从js文件中的函数传递到其他文件中的另一个函数 - How to pass a global variable value from a function in a js file to another function in a different file React JS:如何将变量从一个文件传递到另一个文件,该文件不是同一文件的父文件或子文件? - React JS: How to pass variable from one file to another file, which is not parent or child of the same? 如何将变量从一个javascript文件传递到另一个helpers.js文件 - How to pass a variable from one javascript file to another helpers.js file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM