首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >JavaScript -全局变量不变

JavaScript -全局变量不变
EN

Stack Overflow用户
提问于 2013-03-17 11:13:59
回答 2查看 1K关注 0票数 1

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

代码语言:javascript
运行
AI代码解释
复制
<input type="file" id="input" multiple onchange="readFiles(this.files)">

然后在外部JavaScript文件中:

代码语言:javascript
运行
AI代码解释
复制
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!“。

在这方面的任何帮助都将非常感谢。这是一项任务,非常紧急。

谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-03-17 11:34:23

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

如果要将function readFiles(fileList) {...}更改为window.readFiles = function (fileList) {...},则test将显示为[object File]

jsfiddle.net

我使用parent.document.getElementById('main').contentWindow.document;行是因为我认为它不好( it's fire error =)。

票数 1
EN

Stack Overflow用户

发布于 2013-03-17 11:26:59

您的问题出在var doc = parent.document.getElementById('main').contentWindow.document;上,而不是全局变量。而是您用于文件的作用域。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15460122

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文