javascript - 如何使用数据表仅对一列应用搜索过滤器
问题描述
我有一张表,我想在特定列上应用搜索过滤器。我看到了许多有关如何执行此操作的链接,但是在我的代码中,当我插入一个 javascript 块来执行过滤器时,没有任何显示。
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
</head>
<body>
<table id="example">
<thead>
<tr><th>Sites</th></tr>
</thead>
<tbody>
<tr><td>SitePoint</td></tr>
<tr><td>Learnable</td></tr>
<tr><td>Flippa</td></tr>
</tbody>
</table>
<script>
$(function(){
$("#example").dataTable();
})
</script>
我的困惑是这段代码在哪里(适合主代码)?
<script>
$(document).ready(function() {
// 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+'"
/>' );
} );
// DataTable
var table = $('#example').DataTable();
// 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>
解决方案
从他们的来源:
$('#example thead tr').clone(true).appendTo( '#example thead' );
$('#example thead tr:eq(1) th').each( function (i) {
var title = $(this).text();
$(this).html( '<input type="text" placeholder="Search '+title+'" />' );
$( 'input', this ).on( 'keyup change', function () {
if ( table.column(i).search() !== this.value ) {
table
.column(i)
.search( this.value )
.draw();
}
} );
} );
var table = $('#example').DataTable( {
orderCellsTop: true,
fixedHeader: true
} );
这段代码在 DOM 被渲染后执行。
克隆 id 用于修复表列名称从页面滚动。你也需要这个脚本。
推荐阅读
- javascript - 当我使用 javascript 加载图像时,$_FILES 为空
- javascript - html2canvas 未捕获日期选择器
- python - 两个数据应该使用 python 在 csv 中输出唯一值
- r - R命令系统的含义(“触摸AAA”)
- javascript - 如何在 chromebook 上使用 javascript 库?
- httprequest - 是否应该使用来自服务器的错误代码来响应为用户自动执行的每天一次的操作以供进一步尝试?
- android - 如何使用 Flutter 从网站上抓取图像?
- wordpress - 如何根据位置自动为我的 Wordpress 网站推荐语言?
- django - Django 消息框架 - 默认情况下缺少 i18n
- html - 如何在选择下拉列表中使用 Angular 9 的选定值