1

我正在尝试将文件列表存储在全局变量中,以便可以通过链接访问单个文件。我有这个 HTML 代码:

<input type="file" id="input" multiple onchange="readFiles(this.files)">

然后在外部 JavaScript 文件中:

theFileList = null;

function test() {
    if (theFileList)
        alert(theFileList[0]);
    else
        alert("It is null!");
}

function readFiles(fileList) {
    if (fileList) {
        // I generate a new page in the "main" frame:
        var doc = parent.document.getElementById('main').contentWindow.document;
        theFileList = fileList;
        test(); // works fine (displays "[object File]").

        // opens html and head tags; writes head section (with stylesheet and external js; closes head and opens body:
        generateHeader(); 
        // create a button to check if global variable is null:
        doc.writeln("<button onclick=\"javascript:test();\">Click</button>");
        // closes body and html tags:
        generateFooter();

        doc.close();
    }
    else
        alert("Something went wrong");
}

如评论中所述,首次加载文件时,测试功能会显示正确的输出。但是,当单击生成的按钮时,输出为“It is null!”。

对此的任何帮助将不胜感激。这是一个任务,非常紧急。

谢谢!

4

2 回答 2

1

你的问题是你的var doc = parent.document.getElementById('main').contentWindow.document;而不是全局变量。但是您用于文件的范围。

于 2013-03-17T11:26:58.877 回答
1

我认为您只是在声明之前尝试使用readFiles它。

如果你将更function readFiles(fileList) {...}改为window.readFiles = function (fileList) {...}thentest会说[object File]

jsfiddle.net

我评论了这条线parent.document.getElementById('main').contentWindow.document;,因为我认为这不好(这是火灾错误=))。

于 2013-03-17T11:34:22.703 回答