如何允许使用自定义确认对话框通过 dropzone 删除多个上传的文件?

How can I allow more than one uploaded file to be removed with dropzone using custom confirm dialogue?

我想覆盖 Dropzone 在删除上传的文件时处理确认对话的默认方式,而我在某种程度上几乎已经做到了。这是我的代码。

Dropzone.confirm = function(question, accepted, rejected) {
    showConfirm(question);
    $(document).on('click', '#accept-confirm', function() {
        hideConfirm();
        accepted();
    });
}

showConfirm = function(question) {
    var confirm_dialogue = '<div id="confirm-dialogue"><span class="question">'+question+'</span><button id="deny-confirm" class="button">Cancel</button><button id="accept-confirm" class="button">Yes</button></div>';
    $('body').append(confirm_dialogue).addClass('is-showing-confirm');
}

hideConfirm = function() {  
    $('body').removeClass('is-showing-confirm');
    let dialogue = document.getElementById('confirm-dialogue');
    dialogue.parentNode.removeChild(dialogue);
}

我可以点击我的删除按钮,然后显示我的自定义确认。我可以确认删除并删除缩略图。

问题是我只能对一张图片执行此操作。对于我想删除的任何其他图像,我只会在我的控制台中收到以下错误。

Uncaught TypeError: Cannot read property 'removeChild' of null

您需要在使用 .on() 之前使用 .off(),因为应用于该按钮的事件会被多次调用,例如,

Dropzone.confirm = function(question, accepted, rejected) {
    showConfirm(question);
    $(document).off('click', '#accept-confirm').on('click', '#accept-confirm', function() {
        hideConfirm();
        accepted();
    });
}

或者您可以使用它一次并将您的函数放在 Dropzone.confirm 之外,例如

Dropzone.confirm = function(question, accepted, rejected) {
     showConfirm(question);
}
// now it will be called once only,
$(document).on('click', '#accept-confirm', function() {
    hideConfirm();
    accepted();
});

要从 DOM 中删除元素,请使用 .remove()

hideConfirm = function() {  
    $('body').removeClass('is-showing-confirm');
    $('#confirm-dialogue').remove();
}

您可以检查元素的长度(您要删除的元素),例如,

dialogue && dialogue.parentNode.removeChild(dialogue);