我在网站上使用jQuery DataTable,但每次按下不同的超链接时,表格中的所有数据都会更改。因此,有没有一种方法可以动态删除整个DataTable并使用数组重新创建另一个包含所有数据的数据。
这里的代码只是计划旧的静态内容,但我知道如何动态获取数组,让我们说当我从python / cherryPy返回时,数组看起来像这样: AR [N] = [" COL1"" COL2"" COL3"" COL4",..."科隆& #34;]:
以下代码是用于在HTML(静态)...
中创建DataTable的静态代码<div id="div1" class="ctnr">
<table id="mainTable1" class="dtable" cellpadding="3" cellspacing="1" border="0">
<thead>
<tr><th>*</th><th>Proposal</th><th>Vote </th><th> For </th><th>dd</th><th>A</th></tr>
</thead>
<tbody id="tbdy">
<tr id="zrow1" class="gradeX"><td><input id="ckb1" type="checkbox" class = "tb" /></td><td id="ppl1" class="ppsal" style="width:55%">BlaBlaBla</td><td>More BlaBlaBla</td><td class="ralign"> CheeCheeChee</td><td class="ralign"> ChooChoo...</td><td class="ralign"> LaLaLa</td></tr>
</tbody>
</table>
</div>
我如何在JavaScript或jQuery中执行此操作?
丹尼斯
答案 0 :(得分:5)
DataTables允许您使用他们称之为“data sources”的编程方式定义表格的结构和数据。
文档中有一些示例。我不确定哪一个适合你,但这里有一些让你入门:
您可以将其与the bDestroy()
method结合使用,以避免重新创建<table>
代码。
另一种方法是重新设置行而不重新创建表。我知道没有setData()方法,但您可以使用fnClearTable()
和fnAddData()
方法来获得相同的结果。您可以在DataTables API docs中了解有关这些方法的更多信息。
答案 1 :(得分:0)
你好我有同样的问题......这就是我解决它的方法......
我在laravel控制器中有这个功能...它基于$ app_id变量循环并动态创建一个表...我必须在运行时将数据表附加到它... < / p>
public function getAppUserProfile(Request $request){
$app_id = $request['appId'];
$configs = Userconfig::with('user')->where('config_id', $app_id)->get();
$ct = 1;
$str = '';
foreach($configs as $config){
// $config->user->id,
$str .= '<tr><td>'. $ct.'</td><td>'.
$config->user->profile->first_name
.'</td><td>'.
$config->user->profile->first_name
.'</td><td>'.
$config->user->profile->first_name
.'</td></tr>';
$ct++;
}
$tb = '<table id="testTable2" class="table table-striped table-bordered"><thead>';
$tb .= '<tr><th>S/N</th><th>USER NAME</th><th>ASSIGN ROLE</th><th>Add</th></tr>';
$tb .= '</thead><tbody>' . $str . '</tbody></table>';
//return json_encode($configs);
}
$ str函数用于保存构造的表数据...并且我将表格直接回显到带有id&#34的div标签中的页面。 panel_data_tb&#34;,这是在javascript文件上完成的..
function showAppUser() {
$('.loading').css('display', 'block');
var appID = $('#app_search').val();
$.ajax({
method: 'get',
url: getauprofile,
data: {appId: appID}
})
.done(function (result) {
// alert('success ' + result);
$('#panel_data_tb').html(result);
$('.loading').css('display', 'none');
//this line here is what initializes the datatable on the
//current table just being created...
//dynamically.. and it worked. perfectly for me..
//******************************************************
$('#panel_data_tb').find('table').DataTable();
//*******************************************************
});
}
最后一行..在Div标签中找到该表并动态初始化其上的datatable()属性。因此,只要您更改表的内容,就会在正在创建的动态表上重新初始化数据表。
我希望这会有所帮助。谢谢。