jquery中的append()确实第二次追加文件

时间:2016-08-02 10:26:54

标签: javascript jquery angularjs

我已经定义了一个类型文件的输入和一个隐藏的表单,

<input type="file" name="attachment0" id="attachment0" custom-on-change="uploadfile" ng-show="attachFile" multiple/>
<form class="hidden" id="myForm" method="post" enctype="multipart/form-data" action="SupportRequest">                                 
</form>

&#34;自定义电平变化&#34;是一个angular指令,在选择文件后调用函数uploadfile()。我的javascript看起来如下所示

var form = $('#myForm');
var n=0;
$scope.attachFile = true;

$scope.uploadfile = function() {                                        
                if(n == 0){
                var filein = $('#attachment0');
                form.append(filein);
                $('#attachment0').test();
                }
                else
                    {
                    if(n==1){
                    var temp = "attachment0" + '_' + n;
                    var file_in = $('#'+temp);
                    form.append(file_in);
                    $('#'+temp).test();}                        
                    }
            };

$.fn.test = function() {
                  return this.each(function(){
                    n++;
                    $(this).attr('id',   this.id + '_' + n);
                    $(this).attr('name', this.name + '_' + n);
                  });
            };

我试图将文件两次附加到myForm表单。当我第二次选择文件时,即使在追加之后,我也看到前面附加的输入id =&#34; attachment0&#34; myForm中没有输入id =&#34; attachment0_1&#34;存在于表单中。 这里我试图多次上传多个文件,这就是为什么我动态地改变test()中输入的id。 我希望在myForm中输入id attachment0和attachment0_1。 有谁知道如何解决这个问题?并解释这种行为。

3 个答案:

答案 0 :(得分:1)

将您的代码从form.append(filein)更改为form.append($(&#39;#attachment0&#39;)。clone())。

然后工作。您应该使用.clone()方法来复制元素。

.append()只是将元素从一个地方移动到另一个地方,但是为了复制,首先使用.clone()创建元素的副本,然后将其附加到表单

答案 1 :(得分:0)

看起来像test函数正在替换id,

$(this).attr('id',   this.id + '_' + n);

答案 2 :(得分:0)

使用ng-repeat会不会更好?像这样:

控制器:

$scope.files = [...] // list of files

$scope.uploadfile = function() {                                        
    // So stuff to get the file
    $scope.files.push(filein);
};

Html:

<!-- Inside the form -->
<div ng-repeat="file in files">{{file}}</div>