2015-04-22 58 views
2

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

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> 

回答

0

我希望这是帮助

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

+0

这不会从JSON中提取任何行,OP需要某种方式来知道单击按钮时与每行相关的ID。 – redbmk

+0

@redbmk不是“iDisplayIndex”变量的用途 –

+0

@ S.Buda那么,ID是从那里来的数据库,在'[我] [0]''。 DataTables允许你对数据集进行排序,所以我想'iDisplayIndex'只是告诉你排序数据集中行的索引。 – redbmk

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的值。你可以做你需要做什么用。