[英]Javascript can't access array from one file to another
In my php page, i'm including 2 .js files, and the first one creates and populates a js array which I need to access in the second .js file. 在我的php页面中,我包括2个.js文件,第一个创建并填充一个我需要在第二个.js文件中访问的js数组。 For some reason, I'm getting an error that the array is undefined when I know for a fact that it's being populated.
出于某种原因,当我知道该数组正在被填充时,我得到一个错误,该数组未定义。 Why is this broken?
为什么这坏了?
What am I doing wrong? 我究竟做错了什么?
Error: ReferenceError: sl is not defined
first.js first.js
var sl = [];
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].value + '">' + j[i].text + '</option>';
sl[j[i].value] = [];
sl[j[i].value]['shopping_list'] = j[i].text;
sl[j[i].value]['is_private']= j[i].is_private;
console.log('printing SL for ' + j[i].value);
console.log(sl[j[i].value]['shopping_list']);
}
second.js second.js
$("#shopping_list_name").val(sl[$("#existing_shopping_lists").val()]['shopping_list']);
Is the code that you cited from first.js inside a function (possibly a $(function() {});
)? 您从first.js引用的代码是否在函数内部(可能是
$(function() {});
)内? JavaScript has functional scoping making the var sl=[]
not global (regardless of order) JavaScript具有功能范围,使
var sl=[]
不全局(无论顺序如何)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.