我有一个用例,其中glyphicon:' +'按钮单击将添加新的html输入:文件类型,但在两个条目之后执行此操作,而不是创建一个新的file_input,正在创建多个。
var firstFileInputClone;
$(document).ready(function() {
firstFileInputClone = $(".file-div").last().clone();
});
function addNewFileInput(){
var newFileElement = firstFileInputClone;
var index = $(".file-div").length;
$(newFileElement).find("input:first").attr("name","file_" + index);
$(newFileElement).insertAfter($(".file-div"));
return true;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="file-div row top10">
<label class="col-md-4 control-label">Upload Attachment</label>
<div class="col-md-6 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-home"></i></span>
<input type="file" name="file_0" class="form-control file-input" />
<span class="input-group-addon"><i class="glyphicon glyphicon-plus" onclick="addNewFileInput()"></i></span>
</div>
</div>
</div>
&#13;
答案 0 :(得分:1)
试试这个。
function addNewFileInput(){
var firstFileInputClone = '';
var index = $(".file-input").length;
firstFileInputClone += '<label class="col-md-4 control-label">Upload Attachment</label>';
firstFileInputClone += '<div class="col-md-6 inputGroupContainer">';
firstFileInputClone += '<div class="input-group">';
firstFileInputClone += '<span class="input-group-addon"><i class="glyphicon glyphicon-home"></i></span>';
firstFileInputClone += ' <input type="file" name="file_'+index+'" class="form-control file-input" />';
firstFileInputClone += ' <span class="input-group-addon"><i class="glyphicon glyphicon-plus" onclick="addNewFileInput()" ></i></span>';
firstFileInputClone += '</div>';
firstFileInputClone += '</div>';
$('.file-div').append(firstFileInputClone);
return true;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="file-div row top10">
<label class="col-md-4 control-label">Upload Attachment</label>
<div class="col-md-6 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-home"></i></span>
<input type="file" name="file_0" class="form-control file-input" />
<span class="input-group-addon"><i class="glyphicon glyphicon-plus" onclick="addNewFileInput()"></i></span>
</div>
</div>
</div>