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

报告相同问题?

悬赏问题

  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题