drh19790711 2016-07-11 05:39
浏览 53
已采纳

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

I created a table where in can add and remove dynamically. I just have a little problem where it comes to deleting a row. I want my first row to be fixed because when I used remove() it deletes the row that I given.

Table:

<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:

<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>

I used last function to delete the row but this only delete one textfield. How can I delete this by 4? Any help would appreciated!!

  • 写回答

2条回答 默认 最新

  • duanjiong5686 2016-07-11 05:54
    关注

    tr represents the row and td represent the row's single cell.

    You should read and explore about HTML tables

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

    Working Demo

    and to keep first row always , Count the tr length , and do the delete operation

     $("#removeRow").click(function()
            {   if($('#customFields tbody tr').length== 1){
    
                // only one row left
                 alert("Cant delete first row")
            }else
            {
            $('#customFields tr:last').remove();
            }
    
            });
    

    And Since your thead has a tr too . So delete using this selection

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

    it will delete tr from tbody only

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算