简体   繁体   中英

Text file reading and handling in JavaScript

I'm trying to write a function in which a text file can be selected, read, and used as a variable which can then be split into an array of individual words. When it tries to run the readAsText method, I get the error that this.files[0] is undefined.

 <pre id="contents"></pre>
 <script type="text/javascript">
        function findWord() { 
            function readFile() {
                var fr = new FileReader();
                fr.onload = function() {
                    document.getElementById('contents').textContent = this.result;
                };
                fr.readAsText(this.files[0]);
            }
            var myText = document.getElementById('fileInput').addEventListener('change', readFile());
            var words = myText.split(" ");
            var foundWord = words[0];
            document.write(foundWord);
        }
</script>
<input type="file" id="fileInput" />
<input type="submit" value="Find Word" onclick="findWord();" />

EventTarget.addEventListener expects a function as second argument.

You pass readFile() as the second argument. readFile() is not a function. It's the result of calling the function readFile . When you call that function (to pass its result to EventTarget.addEventListener ), this.files[0] is undefined, because this still references the global object, which does not have a files property.

Pass readFile as second argument to EventTarget.addEventListener , instead of readFile() .

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