【问题标题】:Javascript File HandlingJavascript文件处理
【发布时间】:2013-12-17 20:30:09
【问题描述】:

我正在尝试使用拖放加载客户端文本文件。我一直在这里查看示例代码和教程: http://www.thebuzzmedia.com/html5-drag-and-drop-and-file-api-tutorial/ 和这里 http://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api

在 reader.onload 事件之前一切正常。

function handleFiles(files) 
{
var file = files[0];
var reader = new FileReader();

//create function to deal with the file once it is loaded 
reader.onload = handleLoadedFile();

// begin the read operation
reader.readAsText(file);

}

function handleLoadedFile(event)
{
alert(event.target.result);
}

我认为文本应该在 event.target.result 中,但事实并非如此!警报不会触发。

【问题讨论】:

  • ...那么会发生什么?
  • 您的 JavaScript 控制台中是否有任何错误?
  • 如果您提供小提琴,请看一下

标签: javascript onload filereader


【解决方案1】:

代替

//create function to deal with the file once it is loaded 
reader.onload = handleLoadedFile();

你应该写

//store reference to function to deal with the file once it is loaded 
reader.onload = handleLoadedFile;

解释:

在编写eventhandler = afunction() 时,事件处理程序存储函数的结果,在您的情况下是undefined,因为您的handleLoadedFile 不返回任何内容。

如果是eventhandler = afunction,则在设置处理程序时不会评估该函数。仅存储对该函数的引用。在事件触发时,将使用 () 运算符评估存储的引用(这可能不是真正正确的名称,但您至少可以认为 () 是一个运算符)。

顺便说一句,这是经验丰富的 JavaScript 程序员经常犯的错误。在某些情况下这是正确的,例如:

reader.onload = createEventListener('success');
reader.onerror = createEventListener('error');

function createEventListener(type) {
    return function(event) {
        var content;
        if (type === 'success') {
            content = processMyFile(event.target.result);
        } else {
            content = 'An Error occurred. Please try another file.';
        }
        $('#content').html(content);
    }
}

因此您可以看到在设置事件处理程序时不使用() 在所有情况下都没有错。我希望我没有让你太困惑,因为上面的结构包含 JavaScript 的一个强大的语言特性(即Closures),这需要一些时间才能很好地理解。

仅供参考:当您引用一个函数时,还有其他方法可以调用它:callapply 只是为了避免 JavaScript 专家的反对意见;-)

附加提示:请不要使用alert() 来调试您的代码。在使用现代浏览器进行测试时(应避免使用 Internet Explorer console.log() 和 console 的其他方法。您会喜欢使用它,因为您不必单击 OK 按钮,也不会像使用 alert 那样显着改变异步操作的行为。阅读 Mastering Console Logging 并尝试使用它 - 你永远不会回头警惕!

【讨论】:

    猜你喜欢
    • 2012-04-16
    • 1970-01-01
    • 2012-05-27
    • 2015-03-09
    • 2015-08-26
    • 2016-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多