我得到了向型別為“file”的 html 輸入添加洗掉功能的作業,該功能可以從多個檔案的串列中洗掉單個檔案。正如您在下面的代碼段中看到的那樣,一次洗掉所有檔案很容易,但是我洗掉某個索引處的一個檔案的功能不起作用。
function remove(i){
document.getElementById('files').files.splice(i, 1);
}
function removeAll(){
document.getElementById("files").value=null;
}
<input id="files" type="file" multiple="multiple">
<button onclick="remove(1)">delete 1st</button>
<button onclick="remove(2)">delete 2nd</button>
<button onclick="remove(3)">delete 3rd</button>
<button onclick="removeAll()">delete all</button>
有什么辦法可以使這個remove()函式起作用嗎?
uj5u.com熱心網友回復:
您需要先將物件從 do??cument.getElementById('files') 轉換為陣列。此外 .splice() 回傳移除的元素。所以你需要將陣列存盤在一個變數中。在此陣列上使用 .splice() 后,陣列將包含其余元素:
function remove(i){
var myFiles = Object.entries(document.getElementById('files').files)
Object.entries(myFiles.splice(i-1, 1)); // make sure to use i-1, not i
console.log(myFiles);
// const obj = Object.assign({}, myFiles ); use this to return it back to an obj
}
function removeAll(){
document.getElementById("files").value=null;
}
<input id="files" type="file" multiple="multiple">
<button onclick="remove(1)">delete 1st</button>
<button onclick="remove(2)">delete 2nd</button>
<button onclick="remove(3)">delete 3rd</button>
<button onclick="removeAll()">delete all</button>
uj5u.com熱心網友回復:
首先,您需要傳播input.files到一個陣列中。
其次,您需要splice()使用索引 "i" ( remove(i)) 作為第一個引數呼叫陣列,最后 - 您指定要使用第二個引數 - 僅洗掉一項arr.splice(i, 1)。
最后,arr根據您的按鈕單擊已洗掉專案。
此外,您需要從“remove(0)”開始您的按鈕,因為陣列從 0 開始。
function remove(i){
//document.getElementById('files').files.splice(i, 1);
const input = document.getElementById('files')
const arr = [...input.files];
arr.splice(i, 1);
console.log(arr);
}
function removeAll(){
document.getElementById("files").value=null;
}
<input id="files" type="file" multiple="multiple">
<button onclick="remove(0)">delete 1st</button>
<button onclick="remove(1)">delete 2nd</button>
<button onclick="remove(2)">delete 3rd</button>
<button onclick="removeAll()">delete all</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/355186.html
標籤:javascript html 文件 文件-io
