是否可以在此代码上创建多个功能?

时间:2014-11-27 16:00:47

标签: javascript html5

在这里,我想尝试为此代码的某些部分创建多个函数。但我不知道该怎么做。当我创建多个函数时,输出不起作用。

因为这是关于加载文件.txt,你可以只加载一个随机的txt文件或只是用一些数字填充txt。

以下是代码:http://jsfiddle.net/3149vvcf/1/

window.onload = function() { //1. and this is the part what i want to create function
    var loadFile = document.getElementById('loadFile'); 
    loadFile.addEventListener('change', function(e) { 
        var file = loadFile.files[0]; 
        var textType = /text.*/; 

        if (file.type.match(textType)) { 
            var read = new FileReader();
            read.readAsText(file); 

            read.onload = function(e) { //2. and this one too
                var result = read.result;
                circle(350, 100, 30, "yellow", "blue", result);
...

我可以将其更改为此代码吗?

function file() { //change it like this?
    var loadFile = document.getElementById('loadFile'); 
    loadFile.addEventListener('change', function(e) { 
        var file = loadFile.files[0]; 
        var textType = /text.*/; 

        if (file.type.match(textType)) { 
            var read = new FileReader();
            read.readAsText(file); 
        }
    }
}

function result(e) {
    var result = read.result;
    circle(350, 100, 30, "yellow", "blue", result);
    file();
}

result();

1 个答案:

答案 0 :(得分:0)

我认为你对那里的功能顺序有些混淆

// this guy should in "result" scope as well
var read;

function file() { //change it like this?
    var loadFile = document.getElementById('loadFile'); 
    loadFile.addEventListener('change', function(e) { 
      var file = loadFile.files[0]; 
      var textType = /text.*/; 

      if (file.type.match(textType)) {
          read = new FileReader();
          read.readAsText(file);

          read.onload = result;
      }
    });
}

function result(e) {
  var result = read.result;
  circle(350, 100, 30, "yellow", "blue", result);
  ... more stuff here
}

// on window load read the file
window.onload = file;