在jQuery DataTables中的所有行前面放一个按钮

时间:2015-04-22 18:37:07

标签: javascript jquery json datatables jquery-datatables

我正在使用jQuery DataTables。它正在填充来自数据库的JSON数据。我无法弄清楚如何在每条记录前显示按钮或链接。我想这样做,以便当用户点击该按钮时,该特定记录将添加到数据库中,因此按钮或链接应包含ID。请帮助解决我的问题。 以下是我使用的代码:

var oTable = $('#jsontable').dataTable();

$.ajax({
  url: 'process.php?method=fetchdata',
  dataType: 'json',
  success: function(s) {
    console.log(s);
    oTable.fnClearTable();
    for (var i = 0; i < s.length; i++) {
      oTable.fnAddData([
        s[i][3],
        s[i][4],
        s[i][0], // this contains id
      ]);
    }
  },
  error: function(e) {
    console.log(e.responseText);
  }
});
<table id="jsontable" class="display table table-bordered" cellspacing="0" width="100%">
  <thead>
    <tr>
      <th>Class Number</th>
      <th>Subject</th>
      <th>ADD</th>
    </tr>
  </thead>
</table>

2 个答案:

答案 0 :(得分:0)

我希望这是帮助

oTable = $('#jsontable').dataTable({
                "fnRowCallback": function (nRow, aaData, iDisplayIndex) {
					//nRow		Row Object
					//aaData	Param
					//iDisplayIndex	Row Index
					$('td:eq(0)', nRow).html("<input type='button'>Button</input>");
                    return nRow;
                }
        });

答案 1 :(得分:0)

你的意思是做这样的事吗? (此外,这可能适用于较旧版本的数据表,现在我考虑一下。这是版本1.9的语法,我猜你会使用更新版本(1.10+)语法可能是差异很小,但应记录在the api docs.

    $('#jsontable').dataTable({
        "sAjaxSource" : "process.php?method=fetchdata",
        "aoColumns" : [
            { "mData": function(source) {
                    return '<input type="button" value=' + source[0] + '/>';
            }},
            { "mData": function(source) {
                    return source[1];
            }},
            { "mData": function(source) {
                    return source[2];
            }}
        }
    });

显然,你的按钮可以看起来你想要的,你可能不希望id存储在值上。你可以用它做你需要的。