所以我有一個用 JavaScript 從 JSON 生成的表。表格里面有一個檔案上傳按鈕,我需要交換影像(所有影像都在同一個檔案夾中,所以我只需要檔案名) 生成程序如下所示
ImageClick = document.createElement('input');
ImageClick.type = "file";
ImageClick.id = "subida"
ImageClick.onChange = handleFiles();
cell.appendChild(ImageClick);
處理檔案函式
function handleFiles() {
const fileList = this.files;
console.log(fileList[])
}
結果看起來像這樣
所以當表生成時,handleFiles 函式被立即觸發,甚至在選擇檔案之前,所以我得到一個
Uncaught TypeError: fileList is undefined
頁面加載后。如果我嘗試加載檔案上傳元素
filesElement = document.getElementById('subida')
我嘗試控制臺記錄我得到的 filesElement
Uncaught TypeError: filesElement is null.
我一直在瀏覽互聯網,但找不到答案。我也不能使用 jQuery
uj5u.com熱心網友回復:
這也將起作用:
ImageClick.addEventListener("change", function(e) {
const fileList = e.target.files;
console.log(fileList);
});
uj5u.com熱心網友回復:
像這樣試試?您可以將事件作為處理程式函式中的引數。
<!DOCTYPE html>
<html>
<body>
<p id="hello">Modify input field to fire the onchange event.</p>
<script>
var element = document.getElementById("hello");
ImageClick = document.createElement('input');
ImageClick.type = "file";
ImageClick.id = "subida"
ImageClick.addEventListener("change", handleFiles);
element.appendChild(ImageClick);
function handleFiles(val) {
const fileList = val.target.files;
console.log(fileList)
}
</script>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/365886.html
標籤:javascript html json dom dom事件
