2011-05-11 60 views
0

我試圖給一個變量分配一個選項卡;但我失敗了。這裏是我的代碼:如何通過JavaScript中給定的選項卡ID將變量分配給變量?

var tab; 
chrome.tabs.get(id, function(t) { 
    tab = t; 
    console.log("tab: " + tab); // here the printed result is right 
}); 
console.log("(after assignment) tab: " + tab); // always get "undefined" 

的代碼很簡單,但我不知道問題出在哪裏?

回答

3

的問題是在異步瀏覽器的API調用,也就是說你沒有收到迴應從他們立即。您可以用這種方法重寫您的代碼,例如:

var tab; 
chrome.tabs.get(id, function(t) { 
    tab = t; 
    console.log("tab: " + tab); // here the printed result is right 

    afterAssignment(); 
}); 

function afterAssignment() { 
    console.log("(after assignment) tab: " + tab); // always get "undefined" 

    //the rest of the code that needs to use tab var 
} 
+0

謝謝。現在結果是正確的。:) – adarliu 2011-05-11 02:03:07