为什么数据表使用“ .row()。remove()”删除其中的一行,但是删除了多行?

时间:2018-08-03 02:51:49

标签: jquery html datatables

我使用此code测试我的添加行和删除行。 核心代码是:

$(function(){      
    $("#table_reach_condition_appoint input").on("blur",function(e){
            var oTable = $("#table_reach_condition_appoint");
            eEle = '';
            var target = e.target;
            oTr = $(target).closest('tr');
            if(oTr.index() == oTable.find('tbody tr').last().index())
            {
                eEle = oTr.clone(true);
                if(
                $.trim($("#table_reach_condition_appoint tbody tr:last td input:eq(0)").val())!=""
                &&
                $.trim($("#table_reach_condition_appoint tbody tr:last td input:eq(1)").val())!=""
                &&
                $.trim($("#table_reach_condition_appoint tbody tr:last td input:eq(2)").val())!=""
                )
                {
                    oTable.append(eEle);
                    $("#table_reach_condition_appoint tbody tr:last input").val("");
                }
            }
            setRowNumber("#table_reach_condition_appoint");
        });

    var table_reach_condition_appoint_datatable = $("#table_reach_condition_appoint").DataTable({
        "paging": false,
        "bFilter": false,
        "bInfo" : false,
        "searching": false,
    } );

  $('#table_reach_condition_appoint').on('click', '.deleteRow', function () {
        var row = $(this).closest("tr"); 
        var nRow = row[0];
        table_reach_condition_appoint_datatable
        .row( $(this).parents('tr') )
        .remove()
        .draw();
        setRowNumber("#table_reach_condition_appoint");
        });

});

function setRowNumber(tableID){
    var rowLength = $(tableID+" tbody tr").length;
    for(var i = 1;i<=rowLength;i++){
        $(tableID +" tbody tr:eq("+(i-1)+") td:first").text(i);
    }
}

第一行,我在三个输入框中输入了文本,例如:enter image description here

然后自动添加新行,如下所示: enter image description here

然后我在第二行输入文本: enter image description here

然后自动添加第三行,如下所示: enter image description here

然后我在第三行输入文字: enter image description here

当我在第三行单击“ X”时,如下所示: enter image description here

仅剩以下一行: enter image description here

这是错误的。我只想删除单击的行。如果只有一行,则无法删除,如何修改我的js?

2 个答案:

答案 0 :(得分:1)

我自己解决了。将onclick事件添加到def number_to_steps(number:, size:) (0..number-1).step(size).map { |i| [i, [i+size, number].min-1] } end number_to_steps(number: 10, size: 3) #=> [[0, 2], [3, 5], [6, 8], [9, 9]] number_to_steps(number: 7, size: 2) #=> [[0, 1], [2, 3], [4, 5], [6, 6]] number_to_steps(number: 8, size: 2) #=> [[0, 1], [2, 3], [4, 5], [6, 7]]

像这样修改代码:

HTML代码:

href

js代码:

<td> <a href="###" class="deleteRow" onclick="delRow(this,'#table_reach_condition_appoint')">X</a></td>

答案 1 :(得分:0)

似乎DataTables并没有意识到您通过Jquery追加的行。

您必须使用DataTables API而不是Jquery append()。

Api:

https://datatables.net/examples/api/add_row.html

我的解决方案:

https://jsfiddle.net/3xgbjk8t/28/