我想使用帶有不顯眼的JavaScript的HTML5 File API。但我只能通過從HTML調用JavaScript函數來實現它。有沒有什麼辦法可以使用File API與不顯眼的JavaScript?如何將HTML5 File API與Unobtrusive JavaScript結合使用?
所有瀏覽器都不支持File API,但我已經在Google Chrome和Firefox中嘗試了此操作。
從這個工程的文檔:
<input type="file" id="input" onchange="handleFiles(this.files)">
而且我這個不顯眼的JavaScript不工作的嘗試:
window.onload = function() {
var input2 = document.getElementById('input2');
input2.addEventListener('onchange', handleFiles);
}
一個完整的例子是下面的和可測試的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>
你爲什麼設置將useCapture爲'真'而不是'FALSE'? – Raynos
@Raynos:沒有特別的原因。默認是false,我會改變它。但在某些瀏覽器中它不是可選的(請參閱note @ https://developer.mozilla.org/en/DOM/element.addEventListener),因此提供值是有用的。 – KooiInc