为jQuery文件上传实现删除按钮 [英] Implementing Remove Buttons for jQuery-File-Upload

查看:290
本文介绍了为jQuery文件上传实现删除按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能会用一个完全错误的想法来解决这个问题,所以让我先解释一下我的情况。

我试图用jQuery-File-Upload实现的目的是让用户选择他们选择上传的文件。他们将被允许选择多个文件。现在不管什么类型,但主要是上传图片。所选文件将出现在每个文件的文件名右侧的删除按钮列表中。如下图所示。





如何实现允许用户从正在等待上传的文件列表中删除所选文件的方法? / p>

一旦用户选择文件,他们将会点击开始上传按钮,开始上传包含在列表中的文件并触发上面的图片。

我已经尝试了一些自己的疑难解答,包括注销按钮被点击时发生的事件,但无法从选择的上传文件列表中删除它。我知道有一个 drop 回调,但我不确定这是我应该使用的。



下面是我的代码。

  $(function(){
$('#fileupload')。fileupload({ b $ b dataType:'json',
url:'../php/',
add:function(e,data){
//$.each(data.files,函数(索引,文件){
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>)
//参见https://stackoverflow.com/questions/26234279/blueimp-jquery-upload-multiple-files- does not-work for the reason for the line for
.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 +'\\\
');
}); * /
//});
$('。btn-danger')。on('click',function(e,data){
//console.log(\"Removing all objects ... \\\
);
//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 {//我试着想我可以调用drop()回调函数,但是我($ data);
} catch(error){
console.log(错误是:+错误) ;
}
});


$ b提交:function(e,data){
$('#start-upload')。 {
//$('#start-upload').addClass('#disabledInput');
console.log(This is the start upload button!);
}) ;
},
done:function(e,data){
/*$.each(data.result.files,function(index,file){
$('< ('。file')。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- ('click',function(){
console.log('Dropped file:'+ file.name +'\\\
');
//});
}); ('。fileuploadsubmit','click',function(e,data){
console.log(Submit button pressed。);


) //data.formData = data.context.find(':input')。seralizeArray();
});
});

最后,所有这些都放在我的 $文件).ready



我意识到这可能是一个这篇文章,但这是两个问题,在这里我想我把它细分成更小的问题。

解决方案

通过点击事件中止上传



首先,我需要告诉你,我已经建立了类似于你的东西。达到这一点后,我问自己同样的问题,最终在这里。不幸的是我不得不帮助自己解决这个问题。

你的基本问题是你正在使用方法签名来进行点击事件( function(e ,数据)),它将覆盖包含add方法( function(e,data))的签名。所以,当你试图删除数据上下文,你实际上正在改变点击事件的数据。所以,只需在click事件中保留变量(或者重命名它们),因为在你的例子中你不需要它们。

这样做后,你最终试图干净地销毁上传。我想通了,这是干净的,首先中止他们,并禁止任何以后提交。

这是一个工作代码示例,应该符合您的需求,并有一些自我解释的评论:

  add:function(e,data){

//将数据上下文附加到集合。
data.context = $('< li class =list-group-item>'+ data.files [0] .name +'< button class =btn btn-danger btn-xs pull < / button>')
.appendTo('。list-group');< i>>< i class =glyphicon glyphicon-trash>< / i>

//在数据上下文的子元素中搜索按钮
//并注册click事件。
data.context.children('button')
.click(function(){
//这个按钮将被禁用
$(this).addClass('disabled ');
//中止数据上传,如果它正在运行
data.abort();
//覆盖插件的默认提交函数
data.submit = function ){return false;};
//可选:删除数据上下文(从集合中获取)
//data.context.remove();
})
;
$ b $,

其他提示: Don不要在JavaScript中使用双引号,因为您需要在HTML标记中将它们转义。



如何加载JavaScript



这个问题比你想象的要复杂得多。这是一个永无止境的讨论符合/干净的HTML标记与页面加载。当选择一个方向时,最终会在onload事件和jQuery之间进行另一个选择。你应该打开另一个问题或尝试找到一个相关的问题。在这样做的同时,我同意把你的脚本放在一个干净的匿名函数中,这个函数在文档准备好后自动加载: $(function(){/ * yourcontent * /});


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. 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.

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.

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?

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)). So while you've been trying to remove the data context you were actually altering the data of the click event. So just leave the variables (or either rename them) in the click event, because in your example you don't need them.

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.

How to load the JavaScript

This question is far more complex than you expect. It's a never-ending discussion of conformity/clean HTML-markup versus page loading. When choosing one direction you end up in another choice between onload-events and 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*/ });.

这篇关于为jQuery文件上传实现删除按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆