简体   繁体   中英

Unable to load additional file after initial file has been loaded

I have a script that loads a .DAT file to be read into an application. When I run the script the first time, the file loads and I'm able to work with the file. However, if I decide I want to replace the initial file(say I made a mistake and loaded the wrong one), I'm not able to, the script errors out. Can anyone explain why?

I get :

Uncaught TypeError: Cannot read property 'files' of undefined

HTML :

<span>DAT File: </span><input type="file" id="selectedFile">

JS :

var selectedFile = $("#selectedFile");
$("#load").on("click", function(){
    selectedFile = selectedFile[0].files[0];
    if(selectedFile){
        readFile(selectedFile);
    }
})
function readFile(file){
    var reader = new FileReader();
    console.log(file);
    var holder;
    var holderArray = [];
    var fileArray = [];
    reader.readAsText(file, "UTF-8");
        reader.onload = function(){
        file = reader.result;
        file = file.split(/\s+/g);
        formatFile(holderArray, 3, holder, file, fileArray);
        for(var i = 0; i < 2; i++){
            formatFile(holderArray, 1, holder, file, fileArray);
        }
        for(var i = 0; i < 2; i++){
            formatFile(holderArray, 2, holder, file, fileArray);
        }
        var meh = file.length / fileArray.length;
        for(var i = 0; i < meh; i++){
            formatFile(holderArray, 5, holder, file, fileArray);
        }
        fileArray.pop();
        processFilleInfo(fileArray);
    }
}

You should define your selectedFile variable inside event :

$("#load").on("click", function(){
    var selectedFile = $("#selectedFile");

    selectedFile = selectedFile[0].files[0];

    if(selectedFile){
        readFile(selectedFile);
    }
})

Hope this helps.

Move var selectedFile = $("#selectedFile"); to inside the click handler for #load.

What is happening is - line 1 you set selectedFile to be the jQuery element. First time you call your load.click method this is what it is. Now you reset the variable selectedFile to be the first file of the DOM element 'selectedFile'. Next time you click selectedFile is now this. It is the file. No longer the DOM element!

It might be easier if you didn't reuse a variable name for different things. This doesn't make it easier to understand what is going on (-:

This is probably a better way of doing it:

https://jsfiddle.net/justinwyllie/znLfhyf1/4/

$("#load").on("click", function(){
    selectedFile = $("#selectedFile")[0].files[0];
    if(selectedFile){
        readFile(selectedFile);
    }
})

It is a nice example of how JavaScript keeps scope in the onClick handler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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