我试图在单击按钮时添加新的输入文本和按钮。
但是我认为我确实进行了硬编码...
我想知道是否有一种方法可以简化这种硬编码。
特别是功能add_reference
。
function add_reference() {
var newGroupDiv = document.createElement('div');
newGroupDiv.className = "form-group row mb-1 new-reference";
var newColFirst = document.createElement('div');
newColFirst.className = "col-sm-3";
var newColSecond = document.createElement('div');
newColSecond.className = "col-sm-9 input-group";
var newInput = document.createElement('input');
newInput.setAttribute('type', 'text');
newInput.className = "form-control mr-2 reference-input";
var newButtonDiv = document.createElement('div');
newButtonDiv.className = "input-group-append";
var newButton = document.createElement('button');
newButton.setAttribute('type', 'button');
newButton.className = "btn btn-block btn-ref btn-outline-info float-right";
var newButtonIcon = document.createElement('i');
newButtonIcon.className = "mdi mdi-plus-circle";
newButton.appendChild(newButtonIcon);
newButtonDiv.appendChild(newButton);
newColSecond.appendChild(newInput);
newColSecond.appendChild(newButtonDiv);
newGroupDiv.appendChild(newColFirst);
newGroupDiv.appendChild(newColSecond);
return newGroupDiv;
};
newGroupDiv = add_reference();
$('.form-fieldset').append(newGroupDiv);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset class="form-fieldset">
<div class="form-group row mb-1">
<label class="col-sm-3 text-left control-label col-form-label" for="reference">REF</label>
<div class="col-sm-9 input-group">
<input class="form-control mr-2 reference-input-first reference-input" id="reference" name="reference" required type="text" value="">
<div class="input-group-append">
<button type="button" class="btn btn-block btn-outline-info btn-ref-first float-right"><i class="mdi mdi-plus-circle"></i></button>
</div>
</div>
</div>
</fieldset>
答案 0 :(得分:0)
使用克隆
$('.form-fieldset').append($(".form-fieldset>div").clone(true));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset class="form-fieldset">
<div class="form-group row mb-1">
<label class="col-sm-3 text-left control-label col-form-label" for="reference">참조</label>
<div class="col-sm-9 input-group">
<input class="form-control mr-2 reference-input-first reference-input" id="reference" name="reference" required type="text" value="">
<div class="input-group-append">
<button type="button" class="btn btn-block btn-outline-info btn-ref-first float-right"><i class="mdi mdi-plus-circle"></i></button>
</div>
</div>
</div>
</fieldset>