这是我遇到过的最恼人的问题:
var appslst = [];
function f1()
{
chrome.management.getAll(function(lst)
{
appslst = lst;
});
}
function f2() // this function isn't working!!
{
var l = appslst.length;
var ind = 0;
while(ind < l)
{
document.getElementById("here").value = document.getElementById("here").value.concat(String(ind), ". ", appslst[ind].name, "\n");
ind += 1;
}
}
function f3()
{
f1();
f2();
}
我相信 appslst
- 因为它是一个全局变量 - 应该在函数 f1()
和 f2()
中看到,但是上面的代码不起作用,我不知道为什么。
另外,我尝试了以下代码(并且它有效):
var appslst = [];
function f1()
{
chrome.management.getAll(function(lst)
{
appslst = lst;
var l = appslst.length;
var ind = 0;
while(ind < l)
{
document.getElementById("here").value = document.getElementById("here").value.concat(String(ind), ". ", appslst[ind].name, "\n");
ind += 1;
}
});
}
更多细节。我正在学习如何构建 Google Chrome 扩展程序。 我已经下载了示例:http://code.google.com/chrome/extensions/examples/extensions/app_launcher.zip通过此链接:http://code.google.com/chrome/extensions/samples.html 。我查看了代码,发现与我编写的代码相同,只是它可以工作!
这是我正在谈论的部分:
function onLoad()
{
chrome.management.getAll(function(info)
{
var appCount = 0;
for (var i = 0; i < info.length; i++) {
if (info[i].isApp) {
appCount++;
}
}
if (appCount == 0) {
$("search").style.display = "none";
$("appstore_link").style.display = "";
return;
}
completeList = info.sort(compareByName);
onSearchInput();
});
}
最佳答案
chrome.management.getAll
是异步的 - 因此您需要传递一个仅当 Chrome 执行完 getAll
时才执行的函数。
这意味着f1(); f2();
将像这样:
f1
被调用getAll
被调用(这就是f1
正在做的事情)f2
被调用- 迭代
appslst
(这就是f2
正在做的事情) - (中间有一段时间)
getAll
已完成;传递给它的函数被调用appslst
填充了来自getAll
的数据(这就是传递的函数正在执行的操作)
换句话说,在调用 f2
时,appslst
仍然为空。因此,您还需要暂停 f2()
:
chrome.management.getAll(function(lst){
appslst = lst;
f2(); // only run when getAll is done and appslst is filled
});
关于javascript - 为什么另一个函数看不到我的全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8183527/