JavaScript 在删除预上传图像时不清除图像数组

JavaScript not clearing image array upon deleting preupload image

本文关键字:图像 清除 数组 删除 JavaScript      更新时间:2023-09-26

我发现了这个JSFIDDLE,它是我试图完成的部分工作示例。 具有预览和可选删除选项的多图像上传。 但是,当您实际点击删除时,它就会出现,预览会消失,表单仍会保留上传的图像。

此错误

也可以通过尝试上传超过允许的 5 张图像来复制,如果您上传 7 张图像,它会提醒您不能拥有那么多图像,但是似乎图像数组保留了 7 张图像并且只是不显示预览。

如何调整脚本以实际清除用户删除的图像,以及不允许输入字段接受超过 5 个图像?

谢谢!

var count=0;
	function handleFileSelect(evt) {
		var $fileUpload = $("input#files[type='file']");
		count=count+parseInt($fileUpload.get(0).files.length);
		
		if (parseInt($fileUpload.get(0).files.length) > 6 || count>5) {
			alert("You can only upload a maximum of 5 files");
			count=count-parseInt($fileUpload.get(0).files.length);
			evt.preventDefault();
			evt.stopPropagation();
			return false;
		}
		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) {
				return function (e) {
					var span = document.createElement('span');
					span.innerHTML = ['<img class="thumb" src="', e.target.result, '" title="', escape(theFile.name), '"/><span class="remove_img_preview"></span>'].join('');
					document.getElementById('list').insertBefore(span, null);
				};
			})(f);
			reader.readAsDataURL(f);
		}
	}
	
	$('#files').change(function(evt){
		handleFileSelect(evt);
	});	 
	$('#list').on('click', '.remove_img_preview',function () {
		$(this).parent('span').remove();
        
        //this is not working...
        var i = array.indexOf($(this));
        if(i != -1) {
            array.splice(i, 1);
        }
        // tried this too:
        //$(this).parent('span').splice( 1, 1 );
        
        count--;
	});
.thumb {
	width:40px;
    height: 40px;
    margin: 0.2em -0.7em 0 0;
}
.remove_img_preview {
    position:relative;
    top:-25px;
    right:5px;
    background:black;
    color:white;
    border-radius:50px;
    font-size:0.9em;
    padding: 0 0.3em 0;
    text-align:center;
    cursor:pointer;
}
.remove_img_preview:before {
    content: "×";
}
<input type="file" id="files" name="image_file_arr[]" multiple>
<br><output id="list"></output>

我可以看到您的代码改进的三个地方:

+创建图像时,添加一个将唯一标识图像的属性

span.innerHTML = '<img class="thumb" data-id="' + i + '" src=" + e.target.result + '" title="' + escape(theFile.name), '"/>'

+删除时获取图像 ID,然后根据其值对原始数组进行切片

var i = $(this).data("id");
array.splice(i, 1);

+循环和读取文件时,如果计数大于 5 则中断循环。