调整 How FileReader.readAsText in HTML5 File API works? 后代码达到我的目的。它给了我一个错误。
Uncaught TypeError: Cannot read property 'addEventListener' of null
我改编的Javascript代码
var button = document.querySelector('#fileInput + button');
var input = document.getElementById('#fileInput');
var text = null;
input.addEventListener("change", addDoc);
button.addEventListener("click", handleText);
function addDoc(event) {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(e) {
text = reader.result;
button.removeAttribute("disabled");
};
reader.onerror = function(err) {
console.log(err, err.loaded, err.loaded === 0, file);
button.removeAttribute("diabled");
};
reader.readAsText(event.target.files[0]);
console.log(reader.readAsText(event.target.files[0]));
}
function handleText() {
addtoPreviousOutput();
changeOutputParagraph(text);
button.setAttribute("disabled", "disabled");
}
function changeOutputParagraph(newText) {
var element = document.getElementById("output");
element.innerHTML = newText;
}
function addtoPreviousOutput() {
var previousOutput = document.getElementById("output").innerHTML;
var previousOutput_sOutput = document.getElementById("previousOutput").innerHTML + "<br />";
console.log(previousOutput);
console.log(previousOutput_sOutput);
document.getElementById("previousOutput").innerHTML = previousOutput_sOutput + previousOutput;
}
我的改编 HTML5 代码
<input type="file" id="fileInput" accept="text/*"/>
<button type="button">Add Document</button>
<p id="output"></p>
我的错误是由什么引起的以及如何修复它? 谢谢,DS_Secret。
最佳答案
当代码
var input = document.getElementById('#fileInput');
input.addEventListener("change", addDoc);
失败并显示消息 Uncaught TypeError: Cannot read property 'addEventListener' of null
,由此可见 document.getElementById('#fileInput')
返回 null。
这意味着不存在 ID 为 '#fileInput'
的元素当代码运行时。这是真的,你只有一个类似的 id-ed 元素 id="fileInput"
,没有前导#
特点。所以设置输入像
var input = document.getElementById('fileInput');
或
var input = document.querySelector('#fileInput');
此外,请确保 JavaScript 代码不会运行得太早。通常,依赖于 DOM 的所有内容都应该只被调用一次 DOMContentLoaded
event已触发,特别是如果您的脚本标签位于文档头中。否则,当 JavaScript 运行时,DOM 可能尚未包含所需的元素。
关于javascript - 来自 "How FIleReader.readAsText in HTML5 File API works"的文件读取器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48199860/