如何从对象FileList

时间:2017-07-23 15:40:13

标签: javascript jquery html5

此代码的功能,选择文件后显示预览图像。在内部,每个键和值都插入到FileList对象中。 显示为预览的每个图像都有一个删除按钮。因此,当您按下它时,图像将从屏幕上消失,在内部,我想从FileList对象中删除相应的键和值。我知道我可以从Object中删除,就像“删除Object.key;”但是,在这种情况下,这不能有效地工作。也许还有其他不同的解决方案。如果您知道是否

,请通知我

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title></title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>

<style>
  .thumb {
    height: 75px;
    border: 1px solid #000;
    margin: 10px 5px 0 0;
  }
</style>

<form id='form' action="data.php" method="post" enctype="multipart/form-data">
<input type="file" id="files" name="files[]" multiple />
<button class="show">Butoon</button>
</form>


<output id="list"></output>

<script>

  $('output').on('click','.del',function(){
    var id = $(this).prev().attr('id');
    id = id.split("_");
    id=  id[1];

    var x = document.getElementById("files").files;

    if(id in x) {
     delete x[' + id + '];  //This line is a problem.
    } 
     console.dir(x);

    $(this).parent().replaceWith();
  });

  function handleFileSelect(evt) {
    var files = evt.target.files;

    for (var i = 0, f; f = files[i]; i++) {

      if (!f.type.match('image.*')) {
        continue;
      }

      var reader = new FileReader();

      reader.onload = (function(theFile, num) {
        return function(e) {
          var span = document.createElement('span');
          span.innerHTML = ['<div class="view"><img id ="img_' + num + ' " class="thumb" src="', e.target.result,
                            '" title="', escape(theFile.name), '"/><div class="del">×</div></div>'].join('');
          document.getElementById('list').insertBefore(span, null);
        };
      })(f, i);
      reader.readAsDataURL(f);
    }
      console.dir(files);
  }

  document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

替换delete x ['+ id +'];用:

x.splice(ID,1);