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

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大