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 能给我一些人生建议吗
  • ¥15 mac电脑,安装charles后无法正常抓包
  • ¥18 visio打开文件一直显示文件未找到
  • ¥15 请教一下,openwrt如何让同一usb储存设备拔插后设备符号不变?
  • ¥30 使用quartz框架进行分布式任务定时调度,启动了两个实例,但是只有一个实例参与调度,另外一个实例没有参与调度,不知道是为什么?请各位帮助看一下原因!!
  • ¥50 怎么获取Ace Editor中的python代码后怎么调用Skulpt执行代码
  • ¥30 fpga基于dds生成幅值相位频率和波形可调的容易信号发生器。
  • ¥15 R语言shiny包和ncdf4包报错
  • ¥15 origin绘制有显著差异的柱状图和聚类热图
  • ¥20 simulink实现滑模控制和pid控制对比,提现前者优势