2013-02-28 49 views
2

我有它處理我的網頁上拖拽文件拖放功能:刪除元素離隊文件清單

function createDropHandlers() { 
    var target = document; 
    if (target === null) { 
    return false; 
    } 

    // attach the 'dragover' event to the container 
    target.addEventListener('dragover', function(event) { 
    event.preventDefault(); 
    }, true); 

    // attach the 'drop' event to the container 
    target.addEventListener('drop', function(event) { 
    event.preventDefault(); 
    var files = event.dataTransfer.files; 

    // if (files.length > 3) 
    // do something like 
    // files.slice(files.length-3, files.length); 

    for (var i = 0; i < files.length; i++) { 
     processFile(files[i]); 
     // ... 
    } 
    }, true); 
} 

我希望做的是在我for循環(與之前的「處理」中的任何文件方式)來檢查是否拖動了3個以上的文件,如果是這樣,只需將「數組」分割成最後3個元素即可。我知道FileList是隻讀的,所以我不知道什麼是我在這裏的選項來實現這一目標?
我不會上傳文件,以及「加工」後,他們和我不需要File對象任何責任。我需要做的就是檢查文件是否是音頻文件,從中讀取一些元數據並在頁面上顯示元數據。

回答

2

slice()是Array的原型的一種方法。而它返回一個新的數組,它可能不在FileList原型中。您可以使用Array.prototype.slice方法並將其應用在文件列表中:

Array.prototype.slice.call(fileList); //will return an array-copy of the filelist 
Array.prototype.slice.call(fileList, 0, 3); //Then simply use the slice arguments at your convenience 

您可以使用(而且經常會看到在JS-庫中的代碼)的論點這一招,也。請注意,切片不會修改原始對象,就像splice()一樣。

你可以查看https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/slice#Array-like關於MDN的解釋。