【问题标题】:Put a button in front of all rows in jQuery DataTables在 jQuery DataTables 中的所有行前面放置一个按钮
【发布时间】:2015-04-22 18:37:07
【问题描述】:

我正在使用 jQuery 数据表。它正在填充来自数据库的 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>

【问题讨论】:

    标签: javascript jquery json datatables jquery-datatables


    【解决方案1】:

    希望对你有帮助

    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;
                    }
            });

    【讨论】:

    • 这不会从 JSON 中提取任何行。 OP 需要某种方式来知道单击按钮时与每一行关联的 ID。
    • @redbmk 这不是 iDisplayIndex 变量的用途吗?
    • @S.Buda 好吧,ID 来自数据库,在s[i][0]。 DataTables 允许您对数据集进行排序,所以我想iDisplayIndex 只是告诉您排序数据集中行的索引。
    • @redbmk 是的,当然,有点略过问题/答案。但是,我认为 Silence Peace 已经很接近了,如果他只使用 aaData 中的 id 字段并将其放入他的input 中,它可能会起作用。
    【解决方案2】:

    你的意思是做这样的事情吗? (另外,这可能适用于旧版本的数据表,现在我考虑了一下。这是 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 存储在值上。你可以用它做你想做的事。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-30
      • 2017-09-23
      • 1970-01-01
      • 2021-01-25
      相关资源
      最近更新 更多