2017-02-27 94 views
0

我使用:从jquery.dataTables.js:https://datatables.netjQuery的Datables删除和添加新行

问题:

如果我删除某些行后添加一个新行,行我删除了回来。

如果我添加1行删除此一个,在我添加其他行,插入2而不是仅仅1

所以我试图存档:

行删除不回被删除。

如果我添加新行只添加1,如果我之前删除了一行也没关系。

HTML:

<table id="example" class="display" width="100%" cellspacing="0"> 
    <thead> 
    <tr> 
     <th>order</th> 
     <th>name</th> 
     <th>country</th> 
     <th>delete</th> 
    </tr> 
    </thead> 
</table> 

<button id="addRow">Add New Row</button> 
<table id="newRow"> 
    <tbody> 
    <tr> 
     <td>Line 2 
     <input type="hidden" value="2" /> </td> 
     <td>DVap 
     <input type="hidden" value="DVap" /> </td> 
     <td> 
     <input type="text" value="22" /> </td> 
     <td> 
     <i class="fa fa-minus-square" aria-hidden="true"></i> </td> 
    </tr> 
    </tbody> 
</table> 

的jQuery:

$(document).ready(function() { 
    var dt = $('#example').dataTable(); 
    dt.fnDestroy(); 

    }); 
    $(document).ready(function() { 
    var url = 'http://www.json-generator.com/api/json/get/bQzyuEGndu?indent=2'; 
    var table = $('#example').DataTable({ 
     ajax: url, 
     rowReorder: { 
     dataSrc: 'order', 
     }, 
     columns: [{ 
     data: 'order' 
     }, { 
     data: 'place' 
     }, { 
     data: 'name' 
     }, { 
     data: 'delete' 
     }], 
     "fnDrawCallback": function(oSettings) { 
     $("i.fa.fa-minus-square").click(function(event) { 
      $(this).closest("tr").remove(); 
     }); 
     } 
    }); 
    // add row 
    $('#addRow').click(function() { 
     //t.row.add([1,2,3]).draw(); 
     var rowHtml = $("#newRow").find("tr")[0].outerHTML 
     console.log(rowHtml); 
     table.row.add($(rowHtml)).draw(); 
    }); 
    }); 

的jsfiddle:http://jsfiddle.net/5L2qy092/3/

回答

1

你应该使用API​​的数据表删除/删除行,其他明智的DataTable不能知道什么是真正删除。

还需要使用initComplete代替,因为每个表绘制时间fnDrawCallback火灾,所以你不希望每次

"initComplete": function(oSettings) { 
    $("i.fa.fa-minus-square").click(function(event) { 
     table.row($(this).closest('tr')).remove().draw(); 
    }); 
    } 

工作添加click event处理JSFIDDLE

编辑

使用jquery delegate click进行动态添加行

"initComplete": function(oSettings) { 
    $(this).on("click", "i.fa.fa-minus-square", function(event) { 
     table.row($(this).closest('tr')).remove().draw(); 
    }); 
    } 
+1

谢谢你这是我在找什么,对不起,但我需要能够删除行添加也将是可能的?:请参阅我的jsfiddle:http://jsfiddle.net/5L2qy092/3/ – Raduken

+1

是,你需要使用'click delegate'。更新小提琴http://jsfiddle.net/5L2qy092/4/ – Jag

+0

非常感谢你的帮助 – Raduken