从另一个 js 文件中获取数组条目
Get array entries from another js file
我的程序结构如下:
index.html:
<html>
<head>
<script src="first.js"></script>
<script src="second.js"></script>
</head>
...</html>
first.js:
"use strict";
var array = [];
$(document).ready(function () {
$("#xy").on("tap", function () {
array.push(new arrayItem());
} ...
second.js:
console.log(array);
在 first.js 中,我将一些对象推送到数组,但是 console.log 在 second.js 中说,我的数组是空的。我究竟做错了什么?谢谢...
您的 console.log(array)
可能在文档准备就绪之前被调用,也就是您的主要应用程序代码运行时。
您应该在将数据添加到数组后将 console.log
移动到主文件,或者在主函数完成后使用回调或事件记录它。
正如以前的用户所说,您的 console.log 会立即 运行 在文档完全加载后填充数组的同时。但是,即使您在加载文档时拥有 console.log 运行,它仍然看不到您的变量。你想要做的是在你的 'tap' 事件中,将数组发送到 second.js 中定义的函数,如下所示:
在first.js
"use strict";
var array = [];
$(document).ready(function () {
$("#xy").on("tap", function () {
array.push(new arrayItem());
someFunction(array);
}
在second.js
function someFunction(array) {
console.log(array);
// Do the rest of your code that requires 'array' here
}
这样,每次触发点击事件时,都会将数组传递给 someFunction。
我的程序结构如下:
index.html:
<html>
<head>
<script src="first.js"></script>
<script src="second.js"></script>
</head>
...</html>
first.js:
"use strict";
var array = [];
$(document).ready(function () {
$("#xy").on("tap", function () {
array.push(new arrayItem());
} ...
second.js:
console.log(array);
在 first.js 中,我将一些对象推送到数组,但是 console.log 在 second.js 中说,我的数组是空的。我究竟做错了什么?谢谢...
您的 console.log(array)
可能在文档准备就绪之前被调用,也就是您的主要应用程序代码运行时。
您应该在将数据添加到数组后将 console.log
移动到主文件,或者在主函数完成后使用回调或事件记录它。
正如以前的用户所说,您的 console.log 会立即 运行 在文档完全加载后填充数组的同时。但是,即使您在加载文档时拥有 console.log 运行,它仍然看不到您的变量。你想要做的是在你的 'tap' 事件中,将数组发送到 second.js 中定义的函数,如下所示:
在first.js
"use strict";
var array = [];
$(document).ready(function () {
$("#xy").on("tap", function () {
array.push(new arrayItem());
someFunction(array);
}
在second.js
function someFunction(array) {
console.log(array);
// Do the rest of your code that requires 'array' here
}
这样,每次触发点击事件时,都会将数组传递给 someFunction。