jQuery附加最后一项

问题描述 投票:0回答:1

我正在尝试借助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;
});
javascript jquery
1个回答
0
投票

所以,我正在调查您的工作。我使用了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')

您将了解发生了什么

© www.soinside.com 2019 - 2024. All rights reserved.