我正在尝试编写一个 java 脚本来读取 chrome 中的文件,并且我正在使用 chrome 的 javascript 调试器。这是脚本:
function myFunction()
{
alert("I am an alert box!");
var e ;
var contents;
var control = document.getElementById("myfile");
files = control.files;
console.log("Filename: " + files[0].name);
var reader = new FileReader();
reader.readAsText(files[0]);
reader.onload = function (e) {
contents = e.target.result;
};
console.log("File contents: " + contents);
console.log("I am an alert box!");console.log("I am an alert box!");
}
</script>
当我运行代码时,内容变量未定义。对此进行了大量讨论,但我还没有找到解决方案。我正在使用 --allow-file-acess-from-files 选项。现在下面的代码以一种奇怪的方式工作:
<script>
function myFunction()
{
alert("I am an alert box!");
var e ;
var contents;
var control = document.getElementById("myfile");
files = control.files;
console.log("Filename: " + files[0].name);
var reader = new FileReader();
reader.readAsText(files[0]);
reader.onload = function (e) {
contents = e.target.result ;
};
console.log(e.target.result);
console.log("I am an alert box!");console.log("I am an alert box!");
}
</script>
它会引发一个错误,即“未捕获的类型错误:无法读取未定义的属性‘目标’”但是在监视表达式窗口中,以下变量显示正在读取文件。
event.target.result: "firmware file ↵:10000000782600204D4B0000B94B0000B94B000092 ↵:10001000B94B0000B94B0000B94B000000000000D4 ↵:10002000000000000000000000000000B94B0000CC ↵:10003000B94B000000000000B94B0000210B00008C ↵:10004000B94B0000B94B0000B94B0000B94B0000A0 ↵:10005000B94B0000B94B0000B94B0000B94B000090 ↵:10006000B94B0000B94B0000B94B0000B94B000080 ↵:10007000B94B0000B94B0000B94B0000B94B000070 ↵:10008000B94B0000B94B0000B94B0000B94B000060 and the same ouput for e.target.result and contents variable.
为什么代码行为如此奇怪?请帮帮我。我对javascripting不是很熟练。