这是我的代码。我正试图从read.onload函数中传递treeContent。我不能让它工作。
控制台显示:outer undefined index.html:18内心世界;index.html:15
<!DOCTYPE html>
<html>
<head>
<title>File reader</title>
<meta charset="UTF-8" />
</head>
<body>
<script>
function read(e) {
let reader = new FileReader();
reader.onload = function (e) {
const treeContent = reader.result;
window.file = treeContent;
console.log('inner ' + window.file);
};
reader.readAsText(e.target.files[0]);
console.log('outer '+ window.file);
}
</script>
<input type="file" onchange="read(event)" />
</body>
</html>
从您发布的内容来看,您似乎从未读取过任何文件。在代码中的某个位置,您应该调用reader.readText(fileToRead(..
看看这个最简单的工作示例:
<!DOCTYPE html>
<html>
<head>
<title>File reader</title>
<meta charset="UTF-8" />
</head>
<body>
<script>
function read(e) {
let reader = new FileReader();
reader.onload = function (e) {
const treeContent = reader.result;
console.log(treeContent);
};
reader.readAsText(e.target.files[0]);
}
</script>
<input type="file" onchange="read(event)" />
</body>
</html>
编辑
如果你需要在另一个函数中访问treeContent,你应该调用onload函数中的函数:
function read(e) {
let reader = new FileReader();
reader.onload = function (e) {
const treeContent = reader.result;
treeContentProcessor(treeContent);
};
reader.readAsText(e.target.files[0]);
}
function treeContentProcessor (content) {
//here is where treeContent is required
console.log(content);
}