我正在用 HTML/Javascript 编写 Google Chrome 的扩展。我正在尝试使用全局变量在两个函数之间传递信息,但是即使我在一个函数中分配了我的变量,当我从另一个函数中读取它时它也没有改变。
var type = 0; //define global variable
window.onload=function(){onCreated()}; //set onCreated function to run after loading HTML
function onCreated()
{
chrome.history.search({'text': ''},function(historyItems){gotHistory(historyItems)});//search for historyItems and then pass them to the gotHistory function
}
function gotHistory(historyItems)
{
var idcount=0;//used to increment the ids of each new element added
for(var count=0; count < historyItems.length; count++)//go through each history item
{
chrome.history.getVisits({'url':historyItems[count].url}, function(visitItems){gotVisits(visitItems)}); //search for visitItems for the url and pass the results to gotVisists function (atm all this function does is assign the global variable to =3)
var body = document.getElementById("outputid");//find the body of the HTML
var newt = document.createElement("p");//create a new element
newt.setAttribute("id","url"+idcount);//give it a unique id
newt.innerHTML = historyItems[count].title;//set the text to say the title of the url
if(type != 0)//if the other function was successful, type=3 and the text should be green
{
newt.style.color="green";
}
body.appendChild(newt);//add the new element to the body
idcount++;
}
}
function gotVisits(visitItems)
{
//assign the global variable to be 3
type = 3;
}
但是,元素永远不会是绿色的。它们应该始终是绿色的。这意味着在函数 gotVisits 中,类型未成功分配给 3。谁能解释这里发生了什么?
干杯,
Matt ps 我意识到 gotVisits 函数在这里真的没用,但我用它来说明一点。实际上,我将使用它将有用的信息传回给