根据我的目的调整How FileReader.readAsText in HTML5 File API works?代码后。它给了我一个错误。
未捕获的TypeError:无法读取属性' addEventListener'为null
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;
}
<input type="file" id="fileInput" accept="text/*"/>
<button type="button">Add Document</button>
<p id="output"></p>
我的错误是什么以及如何解决? 谢谢,DS_Secret。
答案 0 :(得分:2)
当代码
var input = document.getElementById('#fileInput');
input.addEventListener("change", addDoc);
失败并显示消息Uncaught TypeError: Cannot read property 'addEventListener' of null
,因此document.getElementById('#fileInput')
返回null。
反过来,这意味着代码运行时没有ID '#fileInput'
的元素。确实如此,您只有id="fileInput"
的类似id-ed元素,没有前导#
字符。所以设置输入如
var input = document.getElementById('fileInput');
或
var input = document.querySelector('#fileInput');
此外,请确保JavaScript代码不会过早运行。通常,只有在DOMContentLoaded
event触发后才会调用依赖于DOM的所有内容,尤其是当您的脚本标记位于文档头中时。否则,当JavaScript运行时,DOM可能还不包含所需的元素。
答案 1 :(得分:1)
我认为您使用的方法是document.getElementById错误。
尝试使用
var input = document.getElementById('fileInput');
而不是
var input = document.getElementById('#fileInput');