开发者

How to use HTML5 File API with Unobtrusive JavaScript?

I would like to use the HTML5 File API with unobtrusive JavaScript. But I can only get it working by开发者_Go百科 calling JavaScript functions from the HTML. Is there any way to use the File API with unobtrusive JavaScript?

The File API is not supported by all browsers, but I have tried this in Google Chrome and in 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:

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

A complete example is below, and testable on 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


not onchange but

input2.addEventListener('change', handleFiles);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜