Ant*_*ell 4 javascript jquery datatables
所以我认为这可能是数据表库中的一个错误。我能够仅使用他们在 jsfiddle 中的示例代码来重现这一点。
重建步骤:
注意:数据表仍保持过滤状态,但搜索字段现在全部为空。
有没有其他人看到这个或看到我在这里做错了什么?
这是javascript
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jquery.dataTables.js" type="text/javascript"></script>
<script src='https://code.jquery.com/jquery-1.12.4.js'></script>
<script src='https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js' type="text/javascript"></script>
<script src='https://cdn.datatables.net/select/1.2.5/js/dataTables.select.min.js' type="text/javascript"></script>
<script src='https://cdn.datatables.net/buttons/1.5.1/js/dataTables.buttons.min.js' type="text/javascript"></script>
<script src='https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js' type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
const table = $('#example').DataTable({
stateSave: true
});
// Setup - add a text input to each footer cell
$('#example tfoot th').each( function () {
var title = $(this).text();
$(this).html( '<input type="text" placeholder="Search '+title+'" />' );
} );
// Apply the search
table.columns().every( function () {
var that = this;
$( 'input', this.footer() ).on( 'keyup change', function () {
if ( that.search() !== this.value ) {
that
.search( this.value )
.draw();
}
} );
} );
} );
</script>
Run Code Online (Sandbox Code Playgroud)
大部分代码取自此链接 https://datatables.net/examples/api/multi_filter.html
预期的功能是数据表应该在加载之间保存状态,并且搜索框应该在页面重新加载时重新加载过滤后的文本。
那是因为你已经stateSave启用了。这将按原样执行列搜索,它们是 DataTables 的内部元素,但由于您的输入元素是外部的,而 DataTables 不知道它们,因此您必须自己填充这些元素。看看这个例子,它在initComplete:
// Restore state saved values
var state = this.state.loaded();
if (state) {
var val = state.columns[this.index()];
input.val(val.search.search);
}
Run Code Online (Sandbox Code Playgroud)
因此,结合我的代码和上面的答案,我想出了这个解决方案
$(document).ready(function() {
const table = $('#example').DataTable({
stateSave: true
});
// Setup - add a text input to each footer cell
$('#example tfoot th').each( function (index,value) {
var title = $(this).text();
$(this).html( '<input type="text" placeholder="Search '+title+'" value="'+table.column(index).search()+'"/>' );
} );
// Apply the search
table.columns().every( function () {
var that = this;
$( 'input', this.footer() ).on( 'keyup change', function () {
if ( that.search() !== this.value ) {
that
.search( this.value )
.draw();
}
} );
});
});
Run Code Online (Sandbox Code Playgroud)
这里修复的主要代码是
$(this).html( '<input type="text" placeholder="Search '+title+'" value="'+table.column(index).search()+'"/>' );
Run Code Online (Sandbox Code Playgroud)
通过在迭代列时首先获取索引值对
$('#example tfoot th').each( function (index,value)
Run Code Online (Sandbox Code Playgroud)
然后,从上面的答案中窃取,按索引从列中注入搜索值
$(this).html( '<input type="text" placeholder="Search '+title+'" value="'+table.column(index).search()+'"/>' );
Run Code Online (Sandbox Code Playgroud)