简体   繁体   English

为jQuery-File-Upload实现删除按钮

[英]Implementing Remove Buttons for jQuery-File-Upload

I may be approaching this with an entirely wrong idea so let me explain my situation first. 我可能会以完全错误的想法接近这个,所以让我先解释一下我的情况。

What I'm trying to achieve using jQuery-File-Upload is to allow the user to select files they choose to upload. 我想用jQuery-File-Upload实现的目的是允许用户选择他们选择上传的文件。 They will be allowed to select multiple files. 他们将被允许选择多个文件。 For now it doesn't matter what type but they'll mainly be uploading images. 目前无论什么类型都没关系,但它们主要是上传图片。 The selected files will appear in a list with a "remove" button to the right of the filename for each file. 所选文件将显示在列表中,每个文件的文件名右侧都有一个“删除”按钮。 As pictured below. 如下图所示。

jQuery-File-Upload的基本设置

How can I implement a means of allowing the user to remove the file they've selected from the list of files that are awaiting upload? 如何实现允许用户从等待上载的文件列表中删除他们选择的文件的方法?

Once the user feels comfortable with their selection of files they will click the 'Start Upload' button which will begin uploading the files contained in the list and trigger the progress bar pictured above. 一旦用户对他们选择的文件感到满意,他们将点击“开始上传”按钮,该按钮将开始上传列表中包含的文件并触发上图所示的进度条。

I've tried some troubleshooting myself including logging out events that happen when the button is clicked but can't manage to remove it from the list of files selected for upload. 我自己尝试了一些故障排除,包括记录单击按钮时发生的事件,但无法将其从选择上传的文件列表中删除。 I know there is a drop callback but I'm not sure if that's what I should be using. 我知道有一个drop回调,但我不知道这是什么,我应该使用。

Below is my code. 以下是我的代码。

$(function () {
    $('#fileupload').fileupload({
        dataType: 'json',
        url: '../php/',
        add: function (e, data) {
            //$.each(data.files, function(index, file) {
                data.context = $('<li class=\"list-group-item\">')
                    //.html(file.name+"<button type=\"button\" id=\"drop\" class=\"btn btn-danger btn-xs pull-right\"><span class=\"glyphicon glyphicon-remove\"></span></button>")
                    // see https://stackoverflow.com/questions/26234279/blueimp-jquery-upload-multiple-files-doesnt-work for the reason for the line below
                    .html(data.files[0].name+"<button type=\"button\" id=\"drop\" class=\"btn btn-danger btn-xs pull-right\"><span class=\"glyphicon glyphicon-trash\"></span></button>")
                    .appendTo(".list-group");
                /*$('.btn-danger').on('click', function() {
                    console.log('Drop '+file.name+' \n');
                });*/
            //});
            $('.btn-danger').on('click', function(e, data) {
                //console.log("Removing all objects...\n");
                //data.context.remove(data.files[0].name);
                //data.context.remove(data.files[0]);
                e.preventDefault();
                /*var filename = $(this).parent().text();
                console.log("Filename: "+filename);
                data.context.remove(data.files.filename);
                console.log("Clicked the drop button");*/
                try { // here I try thinking that I can call the drop() callback but I'm still trying to wrap my head around how this all works.
                    drop(e, data);
                } catch(error) {
                    console.log("The error was: "+error);
                }
            });


        },
        submit: function (e, data) {
            $('#start-upload').on('click', function() {
                //$('#start-upload').addClass('#disabledInput');
                console.log("This is the start upload button!");
            });
        },
        done: function (e, data) {
            /*$.each(data.result.files, function (index, file) {
                $('<p/>').text(file.name).appendTo('.files').find('#panel-body');
            });*/
        },
        progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $('#progress .bar').css(
                'width',
                progress + '%'
            );
        },
        drop: function (e, data) {
            $.each(data.files, function (index, file) {
                //$('.btn-danger').on('click', function() {
                    console.log('Dropped file: '+ file.name +'\n');
                //});
            });
        }
    }).on('.fileuploadsubmit', 'click', function(e, data) {
        console.log("Submit button pressed.");
        //data.formData = data.context.find(':input').seralizeArray();
    });
});

Lastly, should all of this be placed inside my $(document).ready ? 最后,如果所有这些都放在我的$(document).ready

I do realize that this may be a re-post of this post but that's two questions in one where here I figured I subdivide it into smaller problems. 我确实意识到这可能是这篇文章的重新发布,但这是两个问题,在这里我认为我把它细分为更小的问题。

Abort from upload by click event 通过点击事件上传中止

First I need to tell you, that I've built something similar to you. 首先,我需要告诉你,我已经建立了类似于你的东西。 After reaching that point I asked myself the same questions and ended up here. 达到这一点后,我问自己同样的问题,最后到此为止。 Unfortunatly I had to help myself and solved it. 不幸的是,我不得不帮助自己并解决了它。

Your basic problem is that you are using a method signature for the click event ( function(e, data) ) that will overwrite the signature of the containing add method ( function(e, data) ). 您的基本问题是您正在使用方法签名来执行click事件( function(e, data) ),该事件将覆盖包含add方法( function(e, data) )的签名。 So while you've been trying to remove the data context you were actually altering the data of the click event. 因此,在您尝试删除数据上下文时,您实际上正在更改click事件的数据。 So just leave the variables (or either rename them) in the click event, because in your example you don't need them. 因此,只需在click事件中保留变量(或重命名它们),因为在您的示例中您不需要它们。

After doing that you end up trying to cleanly "destroy" uploads. 在这之后你最终试图干净地“破坏”上传。 I figured out, it's clean to first abort them and disable any later submit. 我想通了,首先中止它们并禁用任何后续提交都很干净。

Here is a working code example that should fit your needs and has some self-explanatory comments: 这是一个适合您需求的工作代码示例,并且有一些不言自明的注释:

add: function (e, data) {

// Append data context to collection.
data.context = $('<li class="list-group-item">'+data.files[0].name+'<button class="btn btn-danger btn-xs pull-right"><i class="glyphicon glyphicon-trash"></i></button>')
    .appendTo('.list-group');

// Search in the children of the data context for the button
// and register the click event.
data.context.children('button')
    .click(function () {
        // This button will be disabled.
        $(this).addClass('disabled');
        // Abort the data upload if it's running.
        data.abort();
        // Overwrite the plugin's default submit function.
        data.submit = function () { return false; };
        // Optional: Remove the data context (thus from collection).
        //data.context.remove();
        })
    ;

},

Additional hint: Don't use double quotation marks for JavaScript, because you need to escape them within the HTML-markup. 附加提示:不要对JavaScript使用双引号,因为您需要在HTML标记中转义它们。

How to load the JavaScript 如何加载JavaScript

This question is far more complex than you expect. 这个问题比你想象的要复杂得多。 It's a never-ending discussion of conformity/clean HTML-markup versus page loading. 这是关于整合/清除HTML标记与页面加载的永无止境的讨论。 When choosing one direction you end up in another choice between onload-events and jQuery. 选择一个方向时,最终会在onload-events和jQuery之间进行另一种选择。 You should open another question or try to find a related one. 您应该打开另一个问题或尝试找到相关的问题。 While doing that I agree with putting your scripts in a clean anonymous function, which is automatically loaded after the document being ready: $(function() { /*yourcontent*/ }); 在这样做时,我同意将脚本放在一个干净的匿名函数中,该函数在文档准备好后自动加载: $(function() { /*yourcontent*/ }); .

According to the Documentation for the plugin there should be a .destroy method, but the docs are pretty fuzzy about how to initialize it, or if its to destroy a file from the array, or just destroy the whole form. 根据插件的文档,应该有一个.destroy方法,但是文档对于如何初始化它,或者它是从数组中销毁文件,还是只是破坏整个表单都非常模糊。 There should be a way, at-least in theory there should be. 应该有一种方法,至少在理论上应该有。

As for the second part, yes. 至于第二部分,是的。 Your code should be in a jQuery initializer such as $(document).ready or the more popular $(function() {}); 您的代码应该在jQuery初始化程序中,例如$(document).ready或更受欢迎的$(function() {});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM