我的代碼中的變量有一個小問題。我有一個在函數外部聲明的變量,但在它之后無法訪問。因此,首先您輸入一個與以下代碼組合的文件:input.addEventListener("change", sefunction);現在這個文件(這是一個 HTML 文件)應該被解析為一個字符串:var htmlInput;var inputFile = "";function sefunction() {if (this.files && this.files[0]) { var myFile = this.files[0]; var reader = new FileReader(); reader.addEventListener('load', function (e) { inputFile = e.target.result; htmlInput = new DOMParser().parseFromString(inputFile, "text/html").documentElement; console.log(htmlInput); //WORKING FINE }); reader.readAsBinaryString(myFile); document.getElementById("starten").disabled = false; document.getElementById("myFile").disabled = true; console.log(htmlInput); //NOT WORKING initialisation2(); }; };然后,為了測試它,我想 console.log htmlInput:function initialisation2() { console.log(htmlInput); //NOT WORKING}現在發生了什么:第一個console.log給了我 的內容htmlInput。第二個和第三個(在initialisation2())中沒有。有人能告訴我為什么嗎?該變量是在第一個函數之外聲明的,因此它應該在代碼的其余部分中可用。我需要像這樣解析 HTML 輸入文件,因為我希望能夠訪問htmlInput.getElementsByTagName('table').
1 回答

大話西游666
TA貢獻1817條經驗 獲得超14個贊
該htmlInput變量在第二個之后被賦值console.log并被initialisation2調用。這是因為FileReader是異步的,所以htmlInput直到undefined文件被讀取為止。
將調用initialisation2移至load回調中將解決此問題:
reader.addEventListener("load", function(e) {
inputFile = e.target.result;
htmlInput = new DOMParser().parseFromString(inputFile, "text/html").documentElement;
initialisation2();
});
我們可以使用模仿文件讀取器異步性的超時來復制正在發生的情況:
var htmlInput;
function sefunction() {
setTimeout(() => {
htmlInput = "Given htmlInput";
initialisation2(); // logs "Given htmlInput"
}, 1000);
initialisation2(); // logs "undefined"
}
function initialisation2() {
console.log(htmlInput);
}
- 1 回答
- 0 關注
- 173 瀏覽
添加回答
舉報
0/150
提交
取消