2014-01-29 73 views
1

我有以下代碼片段,並且我不清楚如何將它一直傳遞到onload函數。如何將變量傳遞給javascript中的回調函數

我試圖在不同的地方定義它,但沒有成功,特別是因爲它的定義需要發生在傳遞給document.on方法的函數中,因爲我想獲得this引用的保留。

$(document).ready(function(e) { 
    $(document).on('click', "#someId", function(e) { 
     e.preventDefault(); 
     var variable = $(this).attr('name'); 

     chrome.fileSystem.chooseEntry({ 
      type: 'openFile', accepts:[{ 
       extensions: ['txt'] 
      }] 
     }, 
     function(fileEntry) { 
      if (!fileEntry) { 
       return; 
      } 
      fileEntry.file(function(file) { 
       var reader = new FileReader(); 
       reader.onload = function(e) { 
        ////******* how to access variable here? *******\\\\ 
        chrome.storage.local.set({'txt': e.target.result}); 
       }; 
       reader.readAsArrayBuffer(file); 
      }); 
     }); 
    }); 
}); 

我需要訪問variableonload函數內。 我怎麼能通過它?

+0

你不需要傳遞它。它在外部範圍內,因此在範圍鏈中自然可用。 –

+0

@ Beetroot-Beetroot,我在onload函數內部突出顯示並尋找變量作用域,並且在那裏我看不到變量。另外,當我嘗試在控制檯中獲取值時,我得到ReferenceError:變量未定義 – supercalifragilistichespirali

+0

在這種情況下,我錯誤地理解了問題,或者您正在運行與上面顯示的代碼不同的代碼。 –

回答

0

你可以利用closures這樣做:

onload = function() { 
    var variable; 
    $(document).on('click', "#someId", function(e) { 
     variable = $(this).attr('name'); 
     // use variable here 
    }); 
    // and here 
}; 
+0

感謝這個工作。 – supercalifragilistichespirali

0

如果我正確地分析你的代碼,那麼你應該能夠在您希望使用的變量。這是在正確的範圍內,並有一個關閉,將保持活躍。

使其成爲全球性的,就像在前面的回答將生成simultaneus調用問題 - 變量的值可能在明年調用所覆蓋,你會得到不同的值,當你.onload得到它。

+0

當然,這不保證問題,它只是允許他們 –

+0

我剛剛在onclick處理程序中使用全局變量時出現了令人討厭的錯誤,從此我永遠不會這樣做,只是爲了防止此類錯誤在將來 –

+0

我正在'onload'函數內部着手,看着變量作用域,並且我在那裏看不到'variable'。另外,當我嘗試在控制檯中獲取值時,我得到_ReferenceError:variable is not defined_ – supercalifragilistichespirali

相關問題