javascript - 使用按钮删除图像

标签 javascript

假设我有一个将图像文件推送到阵列上并进行预览的功能

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 现在看起来像这样

enter image description here

现在按钮 X 的目的是删除数组中的图像并删除 html 中的元素。

知道我该怎么做吗?我怎么知道该按钮是针对该特定图像的。

最佳答案

为调用 .removeChild() 的按钮添加一个监听器与 oDiv ,并使用 findIndexaFiles 上数组找到文件的索引,这样就可以拼接出来了:

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/

相关文章:

javascript - 获取本地 API 时发生 Ionic 错误

javascript - 当结果获取 JSON 时,如何在 JQuery 中编写 HTML 代码

php - 使用 AJAX 将变量发送到 php

javascript - 可以在 Node.js 中将变量设置为只读吗

javascript - 正则表达式javascript如何检查aa_bb

javascript - 修复重叠的 html header Javascript 错误?

javascript - hide() jquery 不起作用

javascript - 为什么我的 .js 文件在 eclipse 的 gedit 中启动?

javascript - 如何使用原型(prototype)实现输入掩码?

javascript - javascript数组分配错误