3

我创建了一个数组来存储选定文件的列表。好吧,老实说,我查看了代码,当我意识到它可以满足我的目的时,我就使用了它。现在我需要访问这个数组才能手动删除一些文件,但是我尝试过使用每个扇区的索引,但这不起作用。

这就是我创建数组和存储文件的方式。

 var files = [];
 $("button:first").on("click", function(e) {
                $("<input>").prop({
                    "type": "file",
                    "multiple": true
                }).on("change", function(e) {
                    files.push(this.files);
                }).trigger("click");

});

如果数组 files[] 包含对象 fileList 或从数组中获取索引,我该如何读取它?

4

3 回答 3

4

Here's how I understand your code:

Each time the first button in the dom is clicked a file input dialogue which accepts multiple files is generated. Upon return the dialogue emits a change event with a files variable (a FileList object) attached to the function context (this). Your code pushes the newly created FileList onto the files array. Since the input accepts multiple files each object pushed onto the files array is a FileList object.

So if you want to iterate through all elements in the files array you can put a function in the change event handler:

var files = [];
$("button:first").on("click", function(e) {
    $("<input>").prop({
        "type": "file",
        "multiple": true
    }).on("change", function(e) {
        files.push(this.files);
        iterateFiles(files);
    }).trigger("click");
});


function iterateFiles(filesArray)
{
    for(var i=0; i<filesArray.length; i++){
        for(var j=0; j<filesArray[i].length; j++){
            console.log(filesArray[i][j].name);
            // alternatively: console.log(filesArray[i].item(j).name);
        }
    }
}

In the iterateFiles() function I wrote filesArray[i][j] isn't really a multidimensional array -- but rather a single dimensional array containing FileList objects which behave very much like arrays...except that you can't delete/splice items out of them -- they are read-only.

For more info on why you can't delete see: How do I remove a file from the FileList

于 2013-02-12T03:59:34.237 回答
2

Since you are using jQuery you can use $.grep

files=$.grep( files, function(elementOfArray, indexInArray){
       /* evaluate by index*/
       return indexInArray != someValue;
       /* OR evaluate by element*/
       return  elementOfArray != someOtherValue;
});

API Reference: http://api.jquery.com/jQuery.grep/

于 2013-02-12T03:05:12.347 回答
0

像这样的东西?

for(var i = 0; i < files.length; i++) {
   alert(files[i][0].name);
   if (files[i][0].name == 'file.jpg') {
      files.splice(i, 1) //remove the item
   }
}

也就是说,由于您选择它的方式,每个 FileList 中总是有一个文件。因此,对于每个文件列表,您只对其中的第一个文件感兴趣。对于每个文件,您只需获取此处定义的属性:http: //help.dottoro.com/ljbnqsqf.php

于 2013-02-12T02:06:25.813 回答