HTML5 Javascript FileReader -提取数据到父函数

HTML5 Javascript FileReader - extract data into parent function

本文关键字:函数 数据 提取 Javascript FileReader HTML5      更新时间:2023-09-26

查看HTML文件阅读器。我正在努力从文件阅读器中提取数据。我看到的所有示例都直接使用来自内置FileReader函数的数据。我试图将数据从文件阅读器中取出并将其存储在父类中。然而,我一直没有成功。

function constructTS(name){
    // Variables 
    this.name = name;
    this.csv = "";
}
constructTS.prototype.load = function(files){
    if (window.FileReader) {
        // FileReader are supported.
        var reader = new FileReader();               //Exe#1
        reader.onload = function(e){                 //Exe#2
            var csv = reader.result                  //Exe#5
            var allTextLines = csv.split(/'r'n|'n/); //Exe#6
            var lines = [];                          //Exe#7
            while (allTextLines.length) {            
                lines.push(allTextLines.shift().split(','));
            };                                       //Exe#8
            this.lines = lines;                      //Exe#9

            };
        var x = reader.readAsText(files);            //Exe#3
    } else {
        alert('FileReader yeah.. browser issues.');
    };
    alert(reader.lines[0]);                          //Exe#4
};

this.lines = lines;中的this指的是Filereader类,而不是constructTS类。因此,信息不被存储。我也发现它有点奇怪,它如何运行整个函数,然后只在文件中读取之后。我想这对网页功能是有帮助的。知道如何将数据加载到类中吗?

在JavaScript中this引用闭包上下文:reader.onload中的thisonload方法的上下文,所以reader .

在你的情况下:

function constructTS(name){
    // Variables 
    this.name = name;
    this.csv = "";
}
constructTS.prototype.load = function(files){
    var that = this; //keep a reference on the current context
    if (window.FileReader) {
        // FileReader are supported.
        var reader = new FileReader();               //Exe#1
        reader.onload = function(e){                 //Exe#2
            var csv = reader.result                  //Exe#5
            var allTextLines = csv.split(/'r'n|'n/); //Exe#6
            var lines = [];                          //Exe#7
            while (allTextLines.length) {            
                lines.push(allTextLines.shift().split(','));
            };                                       //Exe#8
            that.lines = lines;                      //Exe#9
        };
        var x = reader.readAsText(files);            //Exe#3
    } else {
        alert('FileReader yeah.. browser issues.');
    };
    alert(reader.lines[0]);                          //Exe#4
};
要了解JavaScript中的this,有很多资源,如https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this

this在这里指未命名的回调函数。试试这个模式:

var outer = this;
reader.onload = function(e){
    ...
    outer.lines = lines;
}
// you can use outer.lines or this.lines here now (they're the same)