Only add unique files to container?

混江龙づ霸主 提交于 2019-12-11 13:45:11

问题


I am using jQuery File Upload plugin - I have the auto upload file upload set to false and the behavior I have is that as files are added I build up a table showing the file name and a remove button to allow the user to remove the file before uploading. There is then an upload all files button?

So if a user adds a file called foo.txt a row will be created. However if they add foo.txt again it will create another row. I want to check the existing table for that scenario and alert that to the user and not create the row.

The code for the upload so far is:

$('#uploadFile').fileupload({
    replaceFileInput: false,
    singleFileUploads: true,
    add: function(event, data) {
        $.each(data.files, function (index, file) {
          var rows = $('#files > tr'); // always getting length 0??

          data.url = myUrl;
          data.type = 'POST';
          data.context = $('<tr>'
            + '<td><strong>Selected File : </strong>' + file.name + '</td>'
            + '<td>&nbsp;</td>'
            + '<td><button type="button" class="removeBtn btn btn-default">'
            + '<span class="glyphicon glyphicon-remove-circle"></span>'
            + 'Remove File</button></td>'
            + '</tr>')
          .appendTo('#files')
          .data('data', data);
    });
});

Note the add function gets called once for each file added which is what I want. However when I try to get the rows in the table I am getting a length of 0 all the time - even when I add a file to the table and then add another file - the second time hitting the add method rows length is still 0 when I was expecting it to be 1?

If I am able to get all the rows before I append then I guess I would have to do a $.each on each row to check the current file name against the filename in the row - if it equals any of them then skip out and not run the append code but instead display an alert?


回答1:


I think the problem is the '#files > tr' selector. It selects all <tr> elements that are direct children of the #files element, but they aren't direct children because the browser inserts a <tbody> element in for you. You could try '#files > tbody > tr' or just '#files tr'.

Here's a jsfiddle that demonstrates this.

You could add the <tbody> yourself and then safely use '#files > tbody > tr'. Of course, you would have to change the call to .append() then so the new <tr> gets appended to the <tbody> instead of the <table>.



来源:https://stackoverflow.com/questions/27283373/only-add-unique-files-to-container

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!