我正在jQuery中创建文件预览和删除功能,但是当我删除预览元素时,它也应该删除数组。
HTML
<div class="col-xs-6">
<div class="btn btn-primary">
<input multiple type="file" id="ImageBrowsers" />
</div>
<hr />
<div id="Gallary">
</div>
</div>
jQuery
$(document).ready(function () {
$("#ImageBrowsers").change(function () {
var File = this.files;
for (var i in File) {
if (typeof File[i] == 'object') {
ImageReader(File[i]);
}
}
});
});
// Image Preview Function
function ImageReader(File) {
var Reader = new FileReader;
var Img = new Image;
Reader.readAsDataURL(File);
Reader.onload = function (_File) {
Img.src = _File.target.result;
Img.onload = function () {
var Height = this.height;
var Width = this.width;
var Type = File.type;
var Size = File.size;
console.log(File.name);
$("#Gallary").append('<div class="thumbnail"><img class="img-responsive" src="' + (_File.target.result) + '"/><div class="caption"><a href="#" onclick="ClearPreview(this,\'' + File.name + '\')"><i class="glyphicon glyphicon-trash"></i></a><p> Size: ' + (Size) + ',' + (Height) + 'x' + (Width) + ', Type: ' + (Type) +'</p></div></div>')
$("#Description").text();
}
}
}
function ClearPreview(Element, FileName) {
var Name = FileName;
$(Element).parents('div.thumbnail').remove();
var Images = $("#ImageBrowsers")[0].files;
for (var x in Images) {
if (FileName == Images[x].name) {
Images[x].remove();
}
}
我知道删除功能不会删除数组,但是我尝试了拼接,也许我做错了,请也帮助我更新文件数组。
答案 0 :(得分:0)
这是从数组中删除元素的正确方法:
Images.slice(x, 1);
但是这会在for循环仍在运行时弄乱数组中的索引,因此您可以执行以下操作:
var indexesForDeletion = [];
for (var x in Images) {
if (FileName == Images[x].name) {
Images[x].remove();
indexesForDeletion.push(x);
}
}
indexesForDeletion.forEach(function(index){
Images.slice(index, 1);
});
indexesForDeletion = [];