我正在尝试将输入 type="file"标记读入 JavaScript 字符串。我知道这应该很简单,但我根本无法让我的代码工作。该文件是纯 .html。这是我所拥有的
<h3>Select location of html file.</h3>
<form onSubmit="submitButtonPressed()">
<input type="file" id="classList" />
<input type="submit" />
</form>
<script>
var reader = new FileReader();
var htmlFile = document.getElementById("classList").files[0]; //read the file selected with the <input> tag
reader.readAsText(htmlFile);
var htmlText = reader.result; //and create a string with the contents
function submitButtonPressed() {
var lengthOfText = htmlText.length;
alert("It is " + lengthOfText + " characters long");
}
</script>
我只是想创建一个字符串,其中包含由输入标记选择的 .html 文件的内容。我不明白为什么 htmlText 不包含 .html 文件的内容,有人可以解释我做错了什么吗?
最佳答案
这就是您的正确答案:
HTML5 File API: How to see the result of readAsText()
reader.onload = function(e) {
// e.target.result should contain the text
};
reader.readAsText(file);
所以我想你必须检查是否按下按钮文件是否已加载,也许它仍在进行中,或者遇到了错误
关于javascript - 将输入标签读入 JavaScript 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20344062/