2017-02-27 50 views
0

我使用:從jquery.dataTables.js:https://datatables.netjQuery的數據表中JSON表中添加新行

我amtrying在我的JSON表中添加一個新行。

我無法讓它工作任何想法爲什麼不呢?

的jsfiddle:http://jsfiddle.net/f7debwj2/17/

HTML:

<table id="example" class="display" width="100%" cellspacing="0"> 
    <thead> 
    <tr> 
     <th>order</th> 
     <th>name</th> 
     <th>country</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> 
    </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/clmDuyndua?indent=2'; 
    var table = $('#example').DataTable({ 
    ajax: url, 
    rowReorder: { 
     dataSrc: 'order', 
    }, 
    columns: [{ 
     data: 'order' 
    }, { 
     data: 'name' 
    }, { 
     data: 'place' 
    }] 
    }); 
    // add row 
    $('#addRow').click(function() { 
    //t.row.add([1,2,3]).draw(); 
    var rowHtml = $("#newRow").find("tr")[0].outerHTML 
    console.log(rowHtml); 
    dt.row.add($(rowHtml)).draw(); 
    }); 
}); 
+1

爲什麼不使用.clone()。appendTo()?編輯:哦 - DataTable可能需要重新啓動html dom ...無論如何 - jsfiddle或代碼片段將是有益的EDIT2 - 哦,我的壞。有jsfiddle –

+0

感謝亞當你能提供一個jsfiddle嗎?謝謝 – Raduken

回答

1

你實際的錯誤是 未捕獲的ReferenceError:DT沒有定義

只要改變table.row.add($(rowHtml))畫出()而不是dt.row.add($(rowHtml ))。draw()裏面的按鈕點擊事件。

+0

這主要是ref的問題。當你在'$(document).ready();之前和之前設置全局作用域'var dt''時,你在訪問它時就沒有問題了。 –

+1

你是對的,但dt也在同一範圍內被摧毀。 – manika