JS:如何访问另一个JS文件中一个JS文件中声明的变量

时间:2018-04-16 14:19:43

标签: javascript html

假设我有 first.js 文件,我声明并使用有效值初始化数组。

.select2-results__options[id*="select2-fruits"] .select2-results__option:nth-child(1) {
  color: red;
}
.select2-results__options[id*="select2-fruits"] .select2-results__option:nth-child(2) {
  color: green;
}
.select2-results__options[id*="select2-fruits"] .select2-results__option:nth-child(3) {
  color: blue;
}

我想在 second.js 文件中使用此变量“arrVar”。我怎么能实现这个目标呢?

我尝试在开头的second.js文件中添加以下语句。

var arrVar = document.getElementsByTagName("label");

但我收到错误“Unexpected Token<”

1 个答案:

答案 0 :(得分:3)

您无法将HTML标记添加到JavaScript文件中。

只要arrVar已在全局范围内定义(不在任何函数内),就应该可以在任何其他文件中访问它,因为它是一个全局变量。

相关问题