预期产出:
基于角色下拉选择每次需要绑定数据表网格
错误:DataTables警告:table id = example - 无法重新初始化DataTable。有关此错误的详细信息,请参阅http://datatables.net/tn/3
UI如下所示:
我的代码:
$(document).ready(function() {
$('#RoleId').change(function() {
var RoleId = $("#RoleId").val();
var SetData = $("#SetRoleMapping");
var url = "/Home/GetRoleMapplingList?RoleId=" + RoleId;
$.ajax({
type: "GET",
url: url,
success: function(data) {
var RoleMapping = JSON.parse(data);
for (var i = 0; i < RoleMapping.length; i++) {
var Data = "<tr class='row_" + RoleMapping[i].Id + "'>" +
"<td>" + RoleMapping[i].Id + "</td>" +
"<td>" + RoleMapping[i].RoleId + "</td>" +
"<td>" + RoleMapping[i].MenuName + "</td>" +
"<td>" + RoleMapping[i].Active + "</td>" +
"</tr>";
SetData.append(Data);
}
var table = $('#example').DataTable({
'paging': true,
'lengthChange': true,
'searching': true,
'ordering': true,
'info': true,
'autoWidth': true
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="~/Content/boostrap/jquery/dist/jquery.min.js"></script>
<script src="~/Content/boostrap/datatables.net/js/jquery.dataTables.min.js"></script>
<table id="example" class="display nowrap dataTable dtr-inline">
<thead>
<tr>
@*
<th><input name="select_all" value="1" id="example-select-all" type="checkbox" /></th>*@
<th>Id</th>
<th>Role Id</th>
<th>Menu Name</th>
<th>Active</th>
</tr>
</thead>
<tfoot>
<tr>
@*
<th>sdfsdf</th>*@
<th>Id</th>
<th>Role Id</th>
<th>Menu Name</th>
<th>Active</th>
</tr>
</tfoot>
<tbody id="SetRoleMapping"></tbody>
</table>
&#13;
答案 0 :(得分:0)
Updated Code:
$('#RoleId').change(function () {
var table;
var RoleId = $("#RoleId").val();
var SetData = $("#SetRoleMapping").empty();
var url = "/Home/GetRoleMapplingList?RoleId=" + RoleId;
$.ajax({
type: "GET",
url: url,
success: function (data) {
var RoleMapping = JSON.parse(data);
for (var i = 0; i < RoleMapping.length; i++) {
var Data = "<tr class='row_" + RoleMapping[i].MenuId + "'>" +
"<td><input type='checkbox' class='chkRow' " + RoleMapping[i].IsActive + " id='chkid1'></td>" +
"<td>" + RoleMapping[i].MenuId + "</td>" +
"<td>" + RoleMapping[i].RoleId + "</td>" +
"<td>" + RoleMapping[i].MenuName + "</td>" +
"</tr>";
SetData.append(Data);
}
table.destroy();
table = $('#example').DataTable({
'destroy': true,
'paging': true,
'lengthChange': true,
'searching': true,
'ordering': true,
'info': true,
'autoWidth': true
}
});
答案 1 :(得分:-1)
您应该在代码的开头将table
对象声明为全局:
var table;
然后你应该在创建一个新实例之前销毁table
的实例:
table.destroy();
然后,您应该在创建DataTable对象时添加destroy
属性:
table = $('#example').DataTable({
'destroy': true,
'paging': true,
'lengthChange': true,
'searching': true,
'ordering': true,
'info': true,
'autoWidth': true
});