我正在尝试借助this创建一个动态输入框列表。
我想在按下“添加”按钮时在第一个输入框之前创建新条目。
我已经尝试过一些.before(), .prepend(), .prependTo()
之类的jQuery方法,但是不起作用。
这是我的代码:
<div id="type-elements" class="controls">
<div class="form-row entry">
<div class="form-inline mb-4">
<a role="button" class="btn btn-link text-success btn-add mr-1" href=""><i class="fas fa-plus"></i></a>
<input type="text" class="form-control mr-1" placeholder="Materia" required name="fields[]">
</div>
<div class="col">
<select class="custom-select" required multiple size="3">
<option disabled>Seleziona una o più classi</option>
<option>2DM</option>
<option>2AM</option>
<option>2DM</option>
<option>2AM</option>
</select>
<br>
<br>
</div>
</div>
$(document).on('click', '.btn-add', function(e)
{
e.preventDefault();
var controlForm = $('.controls:first'),
currentEntry = $(this).parents('.entry:first'),
newEntry = $(currentEntry.clone()).appendTo(controlForm);
newEntry.find('input').val('');
controlForm.find('.entry:not(:last) .btn-add')
.removeClass('btn-add').addClass('btn-remove')
.removeClass('text-success').addClass('text-danger')
.html('<i class="fas fa-minus"></i>');
}).on('click', '.btn-remove', function(e)
{
$(this).parents('.entry:first').remove();
e.preventDefault();
return false;
});
答案 0 :(得分:1)
所以,我正在调查您的工作。我使用了prependTo
newEntry = $(currentEntry.clone()).prependTo(controlForm);
它有效!!
问题与您的课程有关:
controlForm.find('.entry:not(:last) .btn-add')
.removeClass('btn-add').addClass('btn-remove')
.removeClass('btn-success').addClass('btn-danger')
.html('<span class="glyphicon glyphicon-minus"></span>');
它是新条目的开头,但是使用newEntry克隆时将使用css
只需将not(:last)更改为not(:first)
controlForm.find('.entry:not(:first) .btn-add')
您将了解发生了什么