HTML/Javascript で Google Chrome の拡張機能を作成しています。グローバル変数を使用して 2 つの関数間で情報をやり取りしようとしていますが、一方の関数で変数を割り当てても、もう一方の関数から読み取ったときに変更されていません。
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 で type が 3 に正しく割り当てられていないことを意味します。
乾杯、
Matt ps ここでは gotVisits 関数が役に立たないことはわかっていますが、ポイントを示すために使用しています。実際には、私はそれを使用して有用な情報を