JQuery 数据表添加新行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12444296/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQuery Datatables Add new Row
提问by Richard
I'm creating a registration page where someone can register up to 20 other people if they wanted to. So I have these text boxes:
我正在创建一个注册页面,如果有人愿意,可以在其中注册最多 20 个人。所以我有这些文本框:
First Name: <br/><input type="text" name="fname" id="fname" /> <br/>
Last Name: <br/><input type="text" name="lname" id="lname" /> <br/>
Email: <br/><input type="text" name="email" id="email"/> <br/>
This is my html table with my JQuery intialization of DataTables:
这是我的 html 表和我的数据表的 JQuery 初始化:
<div id="tables">
<table id="table" border="1">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
</thead>
</table>
</div>
$('#reg_more').dataTable({
"bLengthChange": false,
"bInfo": false
});
Now I want to put an add button so that the user can input the first and last name, and email and hit add, and it will be put into the table. How do I go about doing this?
现在我想放置一个添加按钮,以便用户可以输入名字和姓氏,以及电子邮件并点击添加,它将被放入表格中。我该怎么做?
回答by User 99x
$(document).ready(function() {
$('#example').dataTable();
$('#addbtn').click(addrow);
} );
function addrow() {
$('#example').dataTable().fnAddData( [
$('#fname').val(),
$('#lname').val(),
$('#email').val() ] );
}
you need to call the addrow() in the button click.
您需要在单击按钮时调用 addrow()。
Add this button in your html code
在您的 html 代码中添加此按钮
<input type="button" value="add" id="addbtn" />
回答by Shoe
Here is the way this is now done in DataTables 1.10
这是现在在 DataTables 1.10 中完成的方式
<input type="button" value="add" id="addbtn" />
var dTable = $('#example').DataTable();
$('#addbtn').on( 'click', function () {
dTable.row.add([
$('#fname').val(),
$('#lname').val(),
$('#email').val()
]).draw();
});
回答by Eliotjse
This can also be helpful but not always at times. I have debugged this myself and will not take much time even if you have more data.
这也可能有帮助,但有时并不总是如此。我自己调试了这个,即使你有更多的数据也不会花太多时间。
var table = $(".tableclassName")["1"]
var tableClone = $(".tableclassName")["3"]
$(yournewrowtext).insertAfter(table.children["1"].children[currentRowId]);
$(yourfirstcolumn).insertAfter(tableClone.children["1"].
children[currentRowId]);
Note: If you are not using fixed column then you can remove this line $(yourfirstcolumn).insertAfter(tableClone.children["1"].
注意:如果您不使用固定列,那么您可以删除此行 $(yourfirstcolumn).insertAfter(tableClone.children["1"]。