简体   繁体   English

如何使用 HTML5 文件 API 和不显眼的 JavaScript?

[英]How to use HTML5 File API with Unobtrusive JavaScript?

I would like to use the HTML5 File API with unobtrusive JavaScript.我想使用 HTML5文件 API和不显眼的 JavaScript。 But I can only get it working by calling JavaScript functions from the HTML.但我只能通过从 HTML 调用 JavaScript 函数来使其工作。 Is there any way to use the File API with unobtrusive JavaScript?有什么方法可以将文件 API 与不显眼的 JavaScript 一起使用?

The File API is not supported by all browsers, but I have tried this in Google Chrome and in Firefox.并非所有浏览器都支持文件 API,但我已在 Google Chrome 和 Firefox 中尝试过此操作。

From the documentation this works:从文档中可以看出:

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

And I have tried with this unobtrusive JavaScript that doesn't work:我已经尝试过这个不起眼的 JavaScript 不起作用:

window.onload = function() {
    var input2 = document.getElementById('input2');
    input2.addEventListener('onchange', handleFiles);
}

A complete example is below, and testable on jsFiddle .下面是一个完整的示例,可在jsFiddle上进行测试。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script>
window.onload = function() {
    var input2 = document.getElementById('input2');
    input2.addEventListener('onchange', handleFiles);
}

function handleFiles(e) {
    alert('got files');
}
</script>
</head>
<body>
<h1>Test</h1>
<input type="file" id="input1" onchange="handleFiles(this.files)"/>
<input type="file" id="input2"/>
</body>
</html>

Try:尝试:

window.onload = function() {
    var input2 = document.getElementById('input2');
    input2.addEventListener('change', handleFiles,false);
    //                       ^not onchange        ^older firefox needs this
}

jsfiddle here jsfiddle在这里

not onchange but不是onchange,而是

input2.addEventListener('change', handleFiles);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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