假设我有一个将图像文件推送到阵列上并进行预览的功能
previewImages: function()
{
let iFileLength = this.files.length;
for (let i = 0; i < this.files.length; i++) {
oHome.aFiles.push(this.files[i]);
}
function readAndPreview(file) {
if (!/\.(jpeg|png|gif|jpg)$/i.test(file.name)) {
return alert(file.name + " is not an image");
}
var reader = new FileReader();
reader.addEventListener("load", function() {
let image = new Image();
image.classList.add('mr-2', 'mt-2', 'w-100', 'h-100');
image.title = file.name;
image.src = this.result;
let oButton = document.createElement("button"); //Button for the remove of image
oButton.classList.add('close');
oButton.type = "button";
oButton.innerHTML= "x";
let oDiv = document.createElement("div");
oDiv.classList.add('col-md-3', 'mt-2');
oDiv.appendChild(oButton);
oDiv.appendChild(image);
oHome.oImgPrev.appendChild(oDiv);
});
reader.readAsDataURL(file);
}
},
选择图片后,html 现在看起来像这样
现在按钮 X 的目的是删除数组中的图像并删除 html 中的元素。
知道我该怎么做吗?我怎么知道该按钮是针对该特定图像的。
最佳答案
为调用 .removeChild()
的按钮添加一个监听器与 oDiv
,并使用 findIndex
在 aFiles
上数组找到文件的索引,这样就可以拼接出来了:
let oButton = document.createElement("button"); //Button for the remove of image
oButton.classList.add('close');
oButton.type = "button";
oButton.innerHTML= "x";
oButton.addEventListener('click', () => {
oHome.oImgPrev.removeChild(oDiv);
oHome.aFiles.splice(oHome.aFiles.indexOf(file), 1);
});
除非您需要一个数组及其索引,否则使用 Set 可能更容易,因为您可以只使用 .add
和 .delete
它的项目,不用担心指标:
oHome.aFiles = new Set();
// To add:
oHome.aFiles.add(this.files[i]);
// To remove:
oHome.aFiles.delete(file);
关于javascript - 使用按钮删除图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57881340/