如何使用.remove函数修复给定行以避免删除

时间:2016-07-11 05:39:28

标签: javascript php jquery twitter-bootstrap-3

我创建了一个表,可以在其中动态添加和删除。我只是在删除一行时有一点问题。我希望我的第一行被修复,因为当我使用remove()时,它会删除我给出的行。

表:

<div class = "col-md-12">

    <table class = "table" id = "customFields">

        <thead>
            <tr>
                <th>Stock No.</th>
                <th>Unit</th>
                <th>Description</th>
                <th>Quantity</th>
            </tr>
        </thead>

        <tbody>
            <tr>
                <td><input type="text" class="form-control"></td>
                <td><input type="text" class="form-control"></td>
                <td><input type="text" class="form-control"></td>
                <td><input type="text" class="form-control"></td>
            </tr>
        </tbody>

    </table>
    <button type = "submit" class = "btn btn-primary" id = "addMore">+ Add</button>
    <button type = "submit" class = "btn btn-danger" id = "removeRow">- Remove</button>

</div>

脚本:

<script>

    $(document).ready(function ()
    {
        $("#addMore").click(function ()
        {
            $("#customFields").append('<tr><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td></tr>');
        });

        $("#removeRow").click(function()
        {
            $('#customFields td:last').remove();
        });
    });

</script>

我使用last函数删除了行,但这只删除了一个文本字段。如何删除4?任何帮助都会赞赏!!

2 个答案:

答案 0 :(得分:2)

tr表示行,td表示行的单个单元格。

您应该阅读并探索HTML tables

 $('#customFields tr:last').remove();

Working Demo

并始终保留第一行,计算tr长度,然后执行删除操作

 $("#removeRow").click(function()
        {   if($('#customFields tbody tr').length== 1){

            // only one row left
             alert("Cant delete first row")
        }else
        {
        $('#customFields tr:last').remove();
        }

        });

由于您的thead也有tr。所以使用此选择删除

$('#customFields tbody tr:last').remove();

它将仅从tr删除tbody

答案 1 :(得分:1)

您应该选择最后一行,而不是最后一个表数据(td)。我的意思是在$('#customFields td:last').remove();语句中,而不是使用td:last,请使用tr:last。

我在此fiddle

中修复了它