简体   繁体   English

Javascript FileReader如何访问reader.onload?

[英]Javascript FileReader how can I access reader.onload?

I am currently learning Javascript. 我目前正在学习Javascript。 I'm working on a program with FileReader. 我正在使用FileReader编写程序。

How can I access variable file for variable perf ? 如何访问变量perf变量file

My code: 我的代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style/style.css">
<title>FileReader</title>
</head>
<body>
<h1>FileReader</h1>
<input type='file' accept='text/plain' onchange='openFile(event)'><br>
Input: <input type="text" id="qi" value="">
<br></br>
<button onclick="check()" class="button buttonB">Check</button>
<p id="ans"></p>
<p id=".same"></p>
<script src="main.js"></script>
</body>
</html>



function check(){
  var text = document.getElementById("qi").value;
  console.log(`Text: ${text}`);

  var perf;       //The value should be `file`

  if (text === perf){
      console.log("Same");
      document.getElementById(".same").innerHTML = "Same";
  } else{
      console.log("Not Same!!!")
      document.getElementById(".same").innerHTML = "Not Same!!!";
  }
}

function openFile(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function(){
var file = reader.result;
console.log(file);
document.getElementById("ans").innerHTML = file;
};
reader.readAsText(input.files[0]);
};

Method 1 : Compare the innerHTML you saved 方法1:比较您保存的innerHTML

var perf = document.getElementById("ans").innerHTML;

Method 2 : Save the variable in a global scope 方法2:在全局范围内保存变量

Just save the variable file in the global scope : 只需将变量file保存在全局范围内:

Replace 更换

var file = reader.result;

By 通过

window.file = reader.result;

And

if (text === perf){

By 通过

if (text === window.file){

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM