删除按钮不起作用

时间:2017-08-16 15:34:50

标签: javascript jquery

我正在尝试在上传多张图片之前添加预览和删除选项,这是我发现的:

$(document).ready(function() {
  if (window.File && window.FileList && window.FileReader) {
    $("#files").on("change", function(e) {
      var files = e.target.files,
        filesLength = files.length;
      for (var i = 0; i < filesLength; i++) {
        var f = files[i]
        var fileReader = new FileReader();
        fileReader.onload = (function(e) {
          var file = e.target;
          $("<span class=\"pip\">" +
            "<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
            "<br/><span class=\"remove\">Remove image</span>" +
            "</span>").insertAfter("#files");
          $(".remove").click(function(){
            $(this).parent(".pip").remove();
          });            
        });
        fileReader.readAsDataURL(f);
      }
    });
  } else {
    alert("Your browser doesn't support to File API")
  }

});

但是上传所有图片的过程中,如何解决此问题?我正在使用php。

1 个答案:

答案 0 :(得分:1)

好的,我正在创建解决问题的示例:

您的HTML

<form method="post" id="sendForm">
  <input type="file" id="files" multiple>
  <input type="submit">
</form>

你的JS

$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
// Array which stores all selected images
var sendData = [];

$("#files").on("change", function(e) {
  var files = e.target.files,
    filesLength = files.length;
  for (var i = 0; i < filesLength; i++) {
    var f = files[i]
    var fileReader = new FileReader();
    fileReader.onload = (function(e) {
      var file = e.target;
      $("<span class=\"pip\">" +
        "<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
        "<br/><span class=\"remove\">Remove image</span>" +
        "</span>").insertAfter("#files");
      // Add all images to array
      sendData.push({file: file, url: e.target.result});

      $(".remove").click(function() {
        var self = $(this).parent().children();
        sendData.map(function(value, currentIndex, data) {
          // Remove only image which removed from preview
          if (self[0].currentSrc === value.url) {
            sendData.splice(currentIndex, 1);
          }
        });
        $(this).parent().remove();
      });

      $("#sendForm").submit(function(e) {
        // Finally post all data to your PHP url that
        $.post("your/php/url", sendData);
      });
    });
    fileReader.readAsDataURL(f);
  }
});
  } else {
    alert("Your browser doesn't support to File API")
  }
});